theJava
theJava

Reputation: 15044

jQuery validation plugin not working for checking special characters

I am trying to add a method to check for special characters at the same time it should allow spaces between words.

jQuery.validator.addMethod("specialChrs",function(element, value) {
        return this.optional(element) || /^[A-Za-z\d= ]+$/.test(value)
}, "Special Characters not permitted");

Below is my signup form.

$("#signupform").validate({

    rules: {
        name: {
            required: true,
            minlength: 3,
            specialChrs: true
        }
    },

    messages: {
        name: {
            required: "name is required",
            minlength: "name must be at least 3 characters"
        }
    }

The method is getting called but its not checking for the regular expression defined and also can anyone explain me what is return this.optional(element) here.

Upvotes: 0

Views: 2412

Answers (1)

malkam
malkam

Reputation: 2355

this.optinal(element) returns true if element is optional.

    jQuery.validator.addMethod("specialChrs", function (element, value) {
            return new RegExp('^[a-zA-Z0-9 ]+$').test(value)
        }, "Special Characters not permitted");


$("#signupform").validate({

    rules: {
        name: {
            required: true,
            minlength: 3,
            specialChrs: true
        }
    },

    messages: {
        name: {
            required: "name is required",
            minlength: "name must be at least 3 characters",
            specialChrs:"Special Characters not permitted",

        }
    }

Upvotes: 1

Related Questions