Validating integer Input using a Mask (Asp .NET MVC 3.0)
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 :
<开发者_JS百科;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:
public class CustomModelBinder : DefaultModelBinder
{
protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value)
{
if (value != null && propertyDescriptor.PropertyType == typeof(string))
{
// always trim strings to clean up database padding
value = ((string)value).Trim();
if ((string)value == string.Empty)
{
value = null;
}
else if ((propertyDescriptor.Attributes[typeof(PhoneNumberAttribute)] != null
|| propertyDescriptor.Attributes[typeof(ZipCodeAttribute)] != null
|| propertyDescriptor.Attributes[typeof(SocialSecurityNumberAttribute)] != null)
&& bindingContext.ValueProvider.GetValue(propertyDescriptor.Name) != null
&& bindingContext.ValueProvider.GetValue(propertyDescriptor.Name).AttemptedValue != null)
{
value =
Regex.Replace(bindingContext.ValueProvider.GetValue(propertyDescriptor.Name).AttemptedValue,
"[^0-9]", "");
}
}
base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
}
}
The custom attributes are just empty Attributes:
public class ZipCodeAttribute : Attribute { }
In the view model, just mark your field like this:
[ZipCode]
public string Zip { get; set; }
Here's how to do the whole thing with maskedinput, editor templates and unobtrusive validation.
精彩评论