user2896120 user2896120 - 4 months ago 16
jQuery Question

Checking if username is valid using jQuery plugin

I am using the jQuery validation plugin to validate forms. I have a username field that I need validated. So far this is what I have:

$(".personal_form").validate({
errorElement: 'div',
rules: {
username: {
required: true,
maxlength: 15,
remote: {
url: "usernameChecker.php",
type: "post",
data: {
username: function() {
return $( "#username" ).val();
},
},
},
},

},

messages: {

username: {
required: "Please enter a username",
maxlength: "Your username should not exceed 15 characters.",
remote: "This username is taken."
},

},

});


I want to make it so that if someone enters an invalid username it'll show an error. For example, if someone entered special characters : "!@#$%^&*()_+=~`-" it'll show an error. Valid usernames are usernames that have letters or numbers. How can I do this?

Answer

Create a custom validation rule that checks for the user name as per your rules like:

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

and add it with your validations

Comments