2 possible options
A. Your could create a custom model binder that strips the invalid characters before the model is bound. Refer this example for a custom model binder that removes white space from posted values. The advantage is that you can register it in global.asax.cs
and your model properties will not contain invalid characters on post back. The disadvantage is that if ModelState
is not valid and you return the view, then the user sees the modified text, which might be confusing (what happened to what I entered?)
B. Create an attribute that inherits from RegularExpressionAttribute
and apply it to all relevant properties
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class MyAttribute : RegularExpressionAttribute
{
public MyAttribute() : base(@"^[^\u20AC]+$")
{
// Add default error message
ErrorMessage = "The value cannot contain the euro symbol";
}
}
and register it in Global.asax.cs
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MyAttribute), typeof(RegularExpressionAttributeAdapter));
The advantage is that it gives both client side and server validation. The disadvantage is that you need to remember to add it to all properties