how to strip special characters with jQuery form validation!

JQuery form validation – How to remove special characters!

i was using a jquery form validation plugin and it was so easy in validating a form. I was stuck in a scenario where i want users to register userID and i dont want them to enter special characters like dots and just want them to enter alphabets, number and underscore in the username.

I went through the documentation of the plugin and there was no such methods to strip the special characters in the plugin.

Finally, i somehow got hold of the code that does the job through regular expression regex that checks for only numbers and a-z

      $.validator.addMethod("noSpecialChars", function(value, element) {
        return this.optional(element) || /^[a-z0-9\_]+$/i.test(value);
    }, "Username must contain only letters, numbers, or underscore.");


All you have to do is call this function from the textbox element. Dont forget to check out the example of addMethod()

//call this from html code within class=required
<input id="cname" name="name" size="25" class="required noSpecialChars" minlength="2" />

Works like a charm!

Similar Posts:


Balakrishnan Prabhu

Mr. Balakrishnan Prabhu is the founder of Corpocrat magazine. He is also the founder of Best Citizenships (BC), assisting wealthy individuals with with global citizenship and residency programs in Europe. His other interests are Linux, Machine learning, Wordpress, etc. You can contact him here

  • Sneha

    Its was very useful, and there was no waste in time to understand the explanation , thanks alot

  • saRca

    Thank u. Very useful and easy to understand. Keep it simple!

  • Fucking Genius!!!

  • Javaman59

    Thanks bud! You saved my neck – I hit this problem 2 minutes from deadline! :))

    BTW – one problem I had was that once the error has been raised it doesn’t clear, and the user has to restart the form. Still, that’s fine by me – this just a failsafe to stop special characters wrecking my program.