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>
<% } %>
Your regular expression should be this:
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.IsValidwill return true.Instead, do this:
Then in your action method: