Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate only 7 digit number?

I'm using mvc. So I want to validate user input number is 7 digit.

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 is not working. How to validate 7 digit numbers?

like image 211
aruni Avatar asked Oct 16 '12 03:10

aruni


3 Answers

Since you're using FluentValidation, you want to use the .Matches validator to perform a regular expression match.

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 could use the GreaterThan and LessThan validators, but the above easier to read. Also note that if a number is something like 0000001 then the above won't work, you'd 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))...
like image 92
Erik Funkenbusch Avatar answered Nov 11 '22 19:11

Erik Funkenbusch


you can use Regex for that

bool x = Regex.IsMatch(valueToValidate, "^\d{7}$");
like image 44
John Woo Avatar answered Nov 11 '22 17:11

John Woo


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

RuleFor(x => x.student_id).Must(x => x.ToString().Length == 7)
like image 1
CherryBlossom Avatar answered Nov 11 '22 19:11

CherryBlossom