DVerde
DVerde

Reputation: 27

How to validate a number with more than you restriction in MVC

[Required(ErrorMessage = "Field is needed")]
[RegularExpression(@"^[0-9]+$", ErrorMessage = "Can only be 9 characters long")]
[Display(Name = "Number")]
 public string Number { get; set; } 

This is what I have. I'm making sure that the number can only have 9 characters, yet I also want it not to accept numbers that don't start with 1 or 2.

So if someone tries to create a 333333333 account, it wouldn't let him. How can I do such a thing?

Here is the View

        <div class="editor-label">
            @Html.LabelFor(u => u.Number)
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(u => u.Number)
            @Html.ValidationMessageFor(u => u.Number)
        </div>

Upvotes: 0

Views: 588

Answers (3)

David Martin
David Martin

Reputation: 12248

Your regex should be something like this:

^[12]{1}\d{8}$
  • [12]{1} = Any character in the list
  • \d{8} = followed by 8 digits

To display more than one error you could combine it with other validation rules such as Range or StringLength although I'm not sure of the order of precendence.

[Required(ErrorMessage = "Field is needed")]
[Range(100000000,299999999, ErrorMessage="Must be 9 characters and start with 1 or 2")]
[RegularExpression(@"^[1-2][0-9]{0,8}$", ErrorMessage = "Can only be 9 characters long and start with 1 or 2")]
[Display(Name = "Number")]
public string Number { get; set; } 

Upvotes: 1

Kaushik Vatsa
Kaushik Vatsa

Reputation: 776

You can put range attribute [Range(1, Int32.MaxValue)]

You can put custom range .. For example for range till 29999999 .. You can put [Range(1, 29999999)].. This will satisfy your requirement that number only start with 1 and 2 ..

Upvotes: 0

matt_lethargic
matt_lethargic

Reputation: 2796

This is the regex you need to only allow 9 numbers and the first has to be 1 or 2

^[1-2][0-9]{0,8}$

So your property will be

[Required(ErrorMessage = "Field is needed")]
[RegularExpression(@"^[1-2][0-9]{0,8}$", ErrorMessage = "Can only be 9 characters long")]
[Display(Name = "Number")]
 public string Number { get; set; } 

NB: Your regex lets you have more than 9 numbers.

I use Debuggex to check my regex out, see yours explained here https://www.debuggex.com/r/O0hseHDUms5Fhh0u

Upvotes: 0

Related Questions