How to correctly use Regular Expression

8

I'm studying about RegularExpression , but I'm not getting it right. In my Model the property CPF must be filled only by numbers:

[RegularExpression(@"[0-9]", ErrorMessage = "CPF deve conter apenas números")]
public string CPF { get; set; }

I wanted to understand how to validate using RegularExpression.

    
asked by anonymous 25.11.2015 / 16:59

2 answers

7

Well, the expression is not exactly right. The correct would be:

[RegularExpression(@"[0-9]{11}", ErrorMessage = "CPF inválido. O CPF deve conter 11 caracteres e apenas dígitos")]
public string CPF { get; set; }

This is because the way it was you are only validating a digit from 0 to 9, not 11 digits.

Validation is done on the client. Make sure the Bundle of jQuery Validation is added to View :

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval");
}
    
25.11.2015 / 17:25
2

Its validation means, the input value of CPF should only receive numbers (or only one) this is expressed by [0-9] the bracket means that it is a list, 0-9 is the allowed character range.

The problem seems to be that only one digit is captured, a 'normal' CPF has 11 numeric digits (there is another 'cpf' cic a yellow one that has a different format), you can inform this through a fixed quantifier {11} which is the number passed between the keys.

    
25.11.2015 / 17:26