kmansoor
kmansoor

Reputation: 4345

jQuery Validator and Optional Fields using Regex

I have an optional field (say "text1") which may either be blank or only alpha-numeric:

jQuery.validator.addMethod("onlyAlphaNumeric", 
        function(value, element) {  
            var regExp = new RegExp(/^[a-zA-Z0-9]+$/);              
            return ((this.optional(element)) || regExp.test(value));
        }
    , "Only aplaha-numeric characters allowed");


$("#student-search-form").validate({
    rules : {
        text1 : {
            optional : true,
            onlyAlphaNumeric: "Only a-n allowed"
        }
    },
    messages: {
        text : {                    
            acceptOnly: " Only alpha-numeric characters allowed"
        }               
    }
});

The problem is no validation happens, so if user enters "!&^%(*" in 'text1', the form gets submitted, no error checks.

Can somebody please tell me what am I doing wrong? Thank you.

Upvotes: 1

Views: 1780

Answers (3)

Sparky
Sparky

Reputation: 98758

This is wrong...

rules : {
    text1 : {
        optional : true,
        onlyAlphaNumeric: "Only a-n allowed"
    }
},

For onlyAlphaNumeric:, you can only put true or false.

I am not too sure about optional: but I know required: is valid... so set required: to false. Alternatively, you could probably leave it out entirely since the validator defaults to fields as being "optional" (required:false) unless you specify otherwise.

rules : {
    text1 : {
        required : false,
        onlyAlphaNumeric: true
    }
},

See this similar answer...

using the jquery validation plugin, how can I add a regex validation on a textbox?

Upvotes: 2

Nabil SADKI
Nabil SADKI

Reputation: 134

I think that your code must be something like this :

// Suppose that your method is well defined
jQuery.validator.addMethod("onlyAlphaNumeric", 
    function(value, element) {  
        var regExp = new RegExp(/^[a-zA-Z0-9]+$/);              
        return ((this.optional(element)) || regExp.test(value));
    }
, "Only alpha-numeric characters allowed");

$("#student-search-form").validate({
    rules : {
        text1 : {
        required : false, // optional must be replaced by required
        onlyAlphaNumeric: true // rules are boolean
        }
    },
    messages: {
        text1 : {
            onlyAlphaNumeric: "I can change my message : Only alpha-numeric characters allowed"
        }
    }
});

Upvotes: 0

Jayendra
Jayendra

Reputation: 52809

you can add optional to the validation method -

http://ajax.microsoft.com/ajax/jquery.validate/1.7/additional-methods.js

jQuery.validator.addMethod("alphanumeric", function(value, element) {
    return this.optional(element) || /^\w+$/i.test(value);
}, "Letters, numbers, spaces or underscores only please");

Validate -

rules : {
     text1 : {
         alphanumeric: true
     }
 },

Upvotes: 0

Related Questions