-1

I have a database that cannot accept non 8-bit chars, and if the user adds a Euro symbol throughout the form the whole thing collapses.

It's a very, very big form and I don't really want to add lines of code everywhere to run a simple replace function - but I can't find any method online to search through a whole form pre-submit, is this possible?

Failing that what's the best way to restrict certain character inputs globally in my web form?

Running ASP.NET MVC4 using lots of jQuery.

aspirant_sensei
  • 1,568
  • 1
  • 16
  • 36

2 Answers2

1

Really not enough info to answer this as best as possible. But I will give it a go. You wouldn't add lines of code everywhere. I assume you are aggregating the form data before submission, at that point you would strip the euro symbol. Assume it is an object..

var formObj = {firstName : "aspiring€", lastName : "programmer€", comment : "I really like euro symbols!!€€€!!" }

$.each(formObj, function( key, value ) {
  formObj[key] = formObj[key].replace(/€/g, '');
});

console.log(formObj);
Joshua Robinson
  • 3,430
  • 1
  • 27
  • 35
0

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

Community
  • 1
  • 1