简体   繁体   中英

Validate form with jquery validation plugin

I'm using jQuery Validation Plugin 1.9.0 (from http://bassistance.de/ ). The problem is that I can't figure out how to validate a text field only if a user type something in it. If the user did not write anything that field should not be treated as required.

Do not set the required rule option -

rules : {
     text1 : {
         required: false, // Or do not specify the option
         minlength: 3 // validation if it has value
     }
 },
if ( value != '' ) {
    // Do your validation here
}

You can pass a function to a validation rule. For instance

$("#demoForm").validate({
               rules: {
                    "requiredField": {sampleRule: function(e){
                                                var input = $(e); 
                                                if(input.val()) 
                                                    return true; 
                                                return false;
                                                }
                                        }                       
                },
                messages : {
                    "requiredField": "This field is invalid"
                }

Where "sampleRule" can be any rule you want eg. "required" or "minlength". The function gives the power to add conditional rule.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM