1

I am using JQuery to validate a form and would like to make the chosenUsername field only accept alphanumeric characters without spaces. I can't seem to find a rule to do this though - what can I do?

$('.theForm').validate({
        errorElement: 'label', //default input error message container
        errorClass: 'help-inline', // default input error message class
        focusInvalid: false, // do not focus the last invalid input
        ignore: "",
        rules: {
            chosenUsername: {
                required: true,
                minlength: 4
            }
        },

        messages: { // custom messages for radio buttons and checkboxes
            message: {
                required: "Please enter a username of at least 4 characters.",
                minlength: "Minimum of 4 characters."
            }

        },

Thank you! Arbiter

Arbiter
  • 486
  • 1
  • 8
  • 21
  • regular expression.... – Bhojendra Rauniyar Jul 31 '14 at 08:36
  • I'm avoiding the use of regex outside of the validation plugin, I'm looking to create a rule outside of this snippet, in the jquery validation plugin, so that I can use the rule again and again in any form that is validated using the same jquery plugin. I hope that makes sense, sorry for not being clear. – Arbiter Jul 31 '14 at 08:39
  • You can refer the solutions in http://stackoverflow.com/questions/5732187/how-to-check-for-alphanumeric-characters – Earth Jul 31 '14 at 08:43
  • You could also include [the plugin's `additional-methods.js` file](http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/additional-methods.js) and just use its `alphanumeric` rule. – Sparky Jul 31 '14 at 13:47

1 Answers1

2

try this:

jQuery.validator.addMethod("alphanumeric", function(value, element) {
    return this.optional(element) || /^[a-zA-Z0-9]+$/.test(value);
}); 

refer this

Community
  • 1
  • 1
logan Sarav
  • 781
  • 6
  • 27
  • Now that's interesting, I can place this in the JQeury validation library can't I? Making the method accessible to any validation snippet? – Arbiter Jul 31 '14 at 08:42
  • yes,you can do it by writing inside the plugin. – logan Sarav Jul 31 '14 at 08:59
  • Instead of writing a custom method, I recommend simply including [the plugin's `additional-methods.js` file](http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/additional-methods.js) so you can use its `alphanumeric` rule. – Sparky Jul 31 '14 at 13:48