Validate jQuery plugin, field not required

2019-07-20 23:36发布

I have got a problem with my form.

For the telephone field, I would like that is not required but in the right format if it's filled (10 digits).

If the form is empty and if it's validated, why the green image is displayed (validClass) ? How to make for that the image is displayed only if the field is completed and in the right format ?

Leave the form blank and confirm to see : http://jsfiddle.net/Xroad/Y3GJr/

$('form').find('.error-message').hide();

$.validator.setDefaults({
    errorClass: 'error-image',
    validClass: 'ok-image',
    errorElement: 'span',
    errorContainer: '#invalid-empty'
});

$("#form-general").validate({

    rules: {
        form_firstname: {
            minlength: 2,
            maxlength: 25,
            regex: /^[-a-zéèçàâA-Z)]+$/
        },
        form_name: {
            minlength: 2,
            maxlength: 25,
            regex: /^[-a-zéèçàâA-Z)]+$/
        },
        form_email: {
            email: true
        },
        form_telephone: {
            digits: true,
            minlength: 10,
            maxlength: 10
        }
    },

        messages: {
        form_firstname: {
            required: "",
            minlength: "Please enter at least {0} characters",
            regex: "Please avoid spaces and special characters"
        },
        form_name: {
            required: "",
            minlength: "Please enter at least {0} characters",
            regex: "Please avoid spaces and special characters"
        },
        form_email: {
            required: "",
            email: "Your email address must be in the format name@domaine.com"
        },
        form_telephone: {
            required: false,
            minlength: "Please enter 10 digits",
            maxlength: "Please enter 10 digits",
            digits: "Please use only numbers"
        },
        form_message: ""
        },

        submitHandler: function(form) {
            $('.btn-validate-group:visible').hide();
            $('.send-wait').fadeIn(300); 
            $.ajax({
                url: form.action,
                type: form.method,
                data: $(form).serialize(),
                success : function() {
                        $('.send-wait').hide(); 
                        $('.send-success').fadeIn(300); 
                      },
                error : function(){
                        $('.send-wait').hide(); 
                        $('.send-error').fadeIn(300);  
                      }
        });
        return false;
        }

});

$.validator.addMethod(
    "regex",
    function(value, element, regexp) {
    var re = new RegExp(regexp);
    return this.optional(element) || re.test(value);
});

2条回答
时光不老,我们不散
2楼-- · 2019-07-21 00:25

For the jQuery Validate plugin, a field will...

  • pass the rules you've assigned so then it's "valid". (gets the "valid" class and no messages)

OR

  • fail at least one of the rules you've assigned so then it's "invalid". (gets the "invalid" class and the error message)

There is nothing between valid and invalid.


Quote OP:

"For the telephone field, I would like that is not required but in the right format if it's filled (10 digits)."

And this is exactly how your jsFiddle is already working.

In your case, the telephone field is not required, it's optional. So when you leave it blank, it has passed validation... it's valid... it can not be anything else.

If it's not left blank, and filled out with letters or anything other than 10 characters, it fails your rules and it's marked as "invalid".

Quote OP:

"If the form is empty and if it's validated, why the green image is displayed (validClass) ?"

See above. A field can only be valid or invalid. An "optional" field is considered "valid" whenever it's left blank.


Side note: Instead of digits and length rules, you could use or modify one of the telephone rules that are already included as part of the additional-methods.js file.


Here is a very crude workaround that will bypass the valid class whenever the field is not required and left blank. (This is not a typical behavior to avoid the "valid" class when the field is technically valid.)

I've assigned a class called optional to the telephone field and used the highlight and unhighlight callback functions as follows...

highlight: function (element, errorClass, validClass) {
    $(element).addClass(errorClass).removeClass(validClass);
},
unhighlight: function (element, errorClass, validClass) {
    if ($(element).hasClass('optional') && $(element).val() == '') {
        $(element).removeClass(errorClass).removeClass(validClass);
    } else {
        $(element).removeClass(errorClass).addClass(validClass);
    }
},

DEMO: http://jsfiddle.net/Y3GJr/3/

NOTE: This code is simplified in that it will not work properly if the form has radio elements. For that case, refer back to the plugin's default callback functions and make the necessary additions.

查看更多
不美不萌又怎样
3楼-- · 2019-07-21 00:32


here is possible solution fiddle
you have forgot the class of input

<input type="text" name="form_telephone" id="form_telephone" class="required requis-image"placeholder="Your phone number" />

I also slightly modified your jQuery code, look at the fiddle
I hope it can help you.

查看更多
登录 后发表回答