Reputation: 27387
I have a model with number of validation rule:
[Required(ErrorMessage = "Number must be enter")]
[RegularExpression("^[0-9]{1,10}$", ErrorMessage = "Your must be enter only integer number between 0-10 simvols")]
public int Number
{
get { return number; }
set { number = value; }
}
so my validation does not work.I check my code, but can not find where I did wrong. This is part of my view template:
<% using (Html.BeginForm())
{%>
<%: Html.ValidationSummary(true) %>
<div class="editor-label">
<p class="number">
Enter number</p>
<%: Html.TextBoxFor(model => model.Number, new {@class = "txtNumber"})%>
<%: Html.ValidationMessageFor(model => model.Number) %>
</div>
<p>
<input type="submit" value="Calculate" class="button" />
</p>
<% } %>
Upvotes: 0
Views: 189
Reputation: 93424
Your regular expression should be this:
"^([0-9]|10)$"
EDIT:
Your real problem, however is that you aren't doing things correctly. You are using an int type in your model. But then you're using FormCollection in your Post action. FormCollection bypasses the model binder, and gives you whatever is typed in.
You should instead be model binding your value, and you should be making it a nullable int in your model. The reason is that int is a value type, and cannot be null. Therefore, it must always contain a value, which in the case of you entering text means that value will be 0, and since 0 passes your validation, the ModelState.IsValid
will return true.
Instead, do this:
[Required(ErrorMessage = "Number must be enter")]
[Range"^[0-9]{1,10}$",
ErrorMessage = "Your must be enter only integer number between 0-10 simvols")]
public int? Number {get;set;}
Then in your action method:
public ActionResult Index(MyModel model) {
if (ModelState.IsValid) {
// model.Number is now an integer already, and IsValid will be false for no number
}
}
Upvotes: 2
Reputation: 3543
Make sure your elements are wrapped inside the html.beginform tags. Validations only work if your controls are inside <form> element.
Upvotes: 1