How to use jQuery Validator custom method on optio

2020-07-22 19:50发布

问题:

I'm using the latest version of the jQuery Validator plugin along with jQuery (1.6.2).

In my optional field for phone number, I have a defaultValue.

HTML:

<input type="text" class="autoclear blur" value="your telephone number" name="Phone" />

I installed a custom method for validating phone numbers as per this thread. The idea is that even though the field is optional, I still want to validate it if/when text is entered.

jQuery/JavaScript:

$(document).ready(function() {

    var nameMsg = "Please enter your full name.",
        emailMsg = "Please enter your email address.",
        emailMsgV = "This is not a valid email address.",
        commentsMsg = "Please enter your comments.";

    $.validator.addMethod('phone', function (value, element) {
        return this.optional(element) || /^[01]?[- .]?\(?[2-9]\d{2}\)?[- .]?\d{3}[- .]?\d{4}$/.test(value);
}, 'This is not a valid number.');

    $('#contactForm').validate({
        onkeyup: false,
        validClass: 'valid',
        rules: {
            Name: {
                required: true
            },
            email: {
                required: true,
                email: true
            },
            Phone: {
                required: false,
                phone: true
            },
            Comments: {
                required: true
            }
        },
        messages: {
            Name: nameMsg,
            email: {
                defaultInvalid: emailMsg,
                required: emailMsg,
                email: emailMsgV
            },
            Comments: commentsMsg
        },
        success: function(error) {
            setTimeout(function() { // Use a mini timeout to make sure the tooltip is rendred before hiding it
                $('#contactForm').find('.valid').qtip('destroy');
            }, 1);
        },
        submitHandler: function(form) {
            $('#contactForm .autoclear').each(function() {
                if (this.value === this.defaultValue) {
                    this.value = '';
                }
            });
            form.submit();
        },
        errorPlacement: function(error, element) {
            $(element).filter(':not(.valid)').qtip({ 
                overwrite: false,
                content: error,
                position: {
                    my: 'left center',
                    at: 'right center'                        
                },
                show: {
                    event: false,
                    ready: true
                },
                hide: false
            }).qtip('option', 'content.text', error);
        } // closes errorPlacement
    }) // closes validate()    

}); // closes document.ready()

The problem is that since I have a defaultValue on this optional field it is getting validated too.

Can the custom method for phone be edited in such a way that it will ignore the defaultValue on the field if the field is left blank?

I tried surrounding the regex with an if/then, but that does not seem to work.

$.validator.addMethod('phone', function (value, element) {
    if (value != element.defaultValue) { 
        return this.optional(element) || /^[01]?[- .]?\(?[2-9]\d{2}\)?[- .]?\d{3}[- .]?\d{4}$/.test(value);
    }
}, 'This is not a valid number');

After thinking about how it works, I know this is the wrong approach... so now I'm lost.

回答1:

Seems that you need to return something from the function you pass to addMethod:

$.validator.addMethod('phone', function (value, element) {
    if (value != element.defaultValue) { 
        return this.optional(element) || /^[01]?[- .]?\(?[2-9]\d{2}\)?[- .]?\d{3}[- .]?\d{4}$/.test(value);
    }
    return true;
}, 'This is not a valid number');

Example: http://jsfiddle.net/L3S9e/