How to use Regular Expression correctly

Asked

Viewed 500 times

8

I’m studying about the RegularExpression, But I don’t quite understand. In my Model the property CPF must be filled in by numbers only:

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

I wanted to understand how to validate using Regularexpression.

  • If it should only contain numbers, why not use a int instead of a string?

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 that the Bundle jQuery Validation is added to View:

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval");
}
  • 1

    It worked here @Gypsy, I will post another question about using Mask in input, but using through model, if you can help me, thanks

  • Just paste the link here for me.

  • http://answall.com/questions/100327/inputmask-pelo-model-visual-basic @Gypsy thanks for helping :)

  • 3

    \d = [0-9] Let’s remember him :D

2

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

The problem seems to be that only one digit is captured, a 'normal' CPF has 11 numeric digits (it has that other 'Cpf' cic an Amarelinho that has a different format), you can report it through a fixed quantifier {11} which is the number passed between the keys.

  • What a grammar, eh, young man?

  • @Ciganomorrisonmendez which part?

  • ...a normal CPF has 11 numeric digits.

  • 1

    @Gypsy omorrisonmendez lol, parallel processing, thank you I will fix.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.