My Model :
public virtual int? NumberTest { get; set; }
My View
@Html.LabelFor(model => model.NumberTest)
<br />
@Html.TextBoxFor(model => model.NumberTest)
I’m using Masked Input Plugin, so I have in my View :
$("#NumberTest").mask("99999-999");
My Html generated :
<input data-val="true" data-val-number="The field NumberTest must be a number." id="NumberTest" name="NumberTest" type="text" value="" />
So it automatically generated a number validation on my Integer input… And I’m using a mask with non-integer char to format number….
This validatior is always called when I fill the input … How can I fix that?
What I did was set the data type to string so it would work with maskedinput, but then in a custom model binder, I stripped out all the non-numeric characters so it could save to the database as an int. You still get both client-side and server-side protection because the user is prevented from entering non-numeric characters by maskedinput client-side and potentially bad characters are filtered out server-side.
Here’s the custom model binder code:
The custom attributes are just empty Attributes:
In the view model, just mark your field like this:
Here’s how to do the whole thing with maskedinput, editor templates and unobtrusive validation.