How to check only 7-digit number?

I am using mvc. Therefore, I want to confirm the user number is 7 digits.

So, I wrote a class.

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")); } 

But it does not work. How to check 7-digit numbers?

+4
source share
3 answers

Since you are using FluentValidation, you want to use the .Matches validator to execute the regular expression.

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

Another option is to do something like this (if student_id is a number):

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

Or you can use the GreaterThan and LessThan validators, but it's easier to read. Also note that if the number is something like 0000001, then the above will not work, you will have to convert it to a string with 7 digits and use the technique below.

if student_id is a string, then something like this:

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

you can use Regex for this

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

You can use the Must extension. And convert the value to a string so you can use .Length

 RuleFor(x => x.student_id).Must(x => x.ToString().Length == 7) 
0
source

Source: https://habr.com/ru/post/1439951/


All Articles