2012-10-16 77 views
4

我正在使用mvc。所以我想驗證用戶輸入的數字是7位數。如何驗證只有7位數字?

所以我寫了一堂課。

public class StduentValidator : AbstractValidator<graduandModel> 
    { 
     public StduentValidator(ILocalizationService localizationService) 
     {       
      RuleFor(x => x.student_id).Equal(7) 
       .WithMessage(localizationService 
        .GetResource("Hire.graduand.Fields.student_id.Required"));     
     } 

但它無法正常工作。 如何驗證7位數字?

+2

看來你使用FluentValidation,這可能是提到一個重要的事情。 –

回答

16

,你要使用的.Matches驗證執行正則表達式匹配。

RuleFor(x => x.student_id).Matches("^\d{7}$").... 

另一種選擇是做這樣的事情(如果student_id數據是一個數字):

RuleFor(x => x.student_id).Must(x => x > 999999 && x < 10000000)... 

或者,您可以使用GREATERTHAN和每種不超過驗證,但上面更容易閱讀。還要注意,如果一個數字類似0000001那麼上述將不起作用,您必須將其轉換爲7位數的字符串並使用下面的技巧。

如果student_id數據是一個字符串,則這樣的事:

int i = 0; 
RuleFor(x => x.student_id).Length(7,7).Must(x => int.TryParse(x, out i))... 
+0

或InclusiveBetween – user1348351

+0

@ user1348351 - 我一直忘記這一點,因爲它不在文檔中,出於某種原因... –

1

可以由於您使用FluentValidation使用Regex

bool x = Regex.IsMatch(valueToValidate, "^\d{7}$");