简体   繁体   中英

jQuery to validation of common phrases

So, I have this web form with validation as such:

jQuery("#firstname").validate({
     expression: "if (VAL) return true; else return false;",
     message: "<br /> First name please."
});

I've been trying to add a validation parameter that won't accept "First Name" as a form value. But I'm not sure how to go about it?

I'm not sure where you found that format, but you need to do something more like this:

$.validator.addMethod('myFirstName',function(v,el){
    return this.optional(el) || v != 'First Name';
}, 'Please specify a first name');

Then in your rules, specify that your first name field needs to use that:

$("form").validate({
    rules: {
        firstName: {
            myFirstName: true,
            required: true
        }
    }
});

The key is that your validator method is passed the form value and the element, so you can do whatever you want in that function to decide whether it is valid input or not. You'll see the return this.optional(el) business in most of these types of plugin methods because they want to allow the field to be blank if it isn't a required field.

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