Pages

Friday, February 17, 2012

Strip special characters with jQuery form validation

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



01
02
03
04
05
06
07
08
09
10
<script>
$(document).ready(function(){
    $.validator.addMethod("noSpecialChars", function(value, element) {
      return this.optional(element) || /^[a-z0-9\_]+$/i.test(value);
  }, "Username must contain only letters, numbers, or underscore.");
  $("#myForm").validate();
});
</script>

All you have to do is call this function from the textbox element.

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

Works like a charm!

No comments:

Post a Comment