验证jQuery插件,不需要字段 [英] Validate jQuery plugin, field not required

查看:149
本文介绍了验证jQuery插件,不需要字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的表单存在问题。



对于电话领域,我希望这不是必需的,但是如果填写的话,它是正确的格式(10位数字)。

如果表单为空且验证通过,为什么会显示绿色图像(validClass)?如何使图像仅在字段完整且格式正确时显示?



将表单留空并确认以查看: http://jsfiddle.net/Xroad/Y3GJr/



<$ p 。$ p> $( '形式')找到( '错误消息')隐藏();

$ .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,
正则表达式:/ ^ [ - a-zéèçàâA-Z)] + $ /
},
form_email:{
email:true
},
form_telephone:{
digits:true,
minlength:10,
maxlength:10
}
},

消息:{
form_firstname:{
required:,
minlength:请输入至少{0}个字符,
正则表达式:请避免使用空格和特殊字符
},
form_name:{
required:,
minlength:请输入至少{0}个字符,
regex:请避免使用空格和特殊字符

form_email:{
required:,
email:您的电子邮件地址必须采用格式name@domaine.com
},
form_telephone:{
required:false,
minlength:请输入10位数字,
maxlength:请输入10位数字,
数字:请只使用数字
},
form_message:
},

submitHandler:function(form){
$( '.btn-验证组:可见')隐藏();
$('。send-wait')。fadeIn(300); $ b $ .ajax({
url:form.action,
type:form.method,
data:$(form).serialize(),
成功:函数(){
$('。send-wait')。hide();
$('。send-success')。fadeIn(300);
},
error:function(){
$('。send-wait')。hide();
$('。send-error')。fadeIn(300);
}
});
返回false;
}

});

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


解决方案

对于jQuery Validate插件, 。


  • 传递你分配的规则,然后它是有效的。 (获得有效的并且没有消息)



p>


  • 至少会失败其中一个规则,因此它是无效的。 (得到无效的 class 和错误信息)



  • 有效和无效之间没有任何区别。






    引用OP:


    对于电话领域,我希望这不是必需的,但如果填写完整(10位数字),则采用正确的格式。


    这就是您的jsFiddle已经在工作的原因。



    在您的情况下,电话不是必需的,它是可选的。所以当你把它留空时,它已通过验证......它是有效的......它不能是其他任何东西。



    如果它没有留空,并填写包含字母或10个字符以外的任何字词,则不符合规则并被标记为无效。

    引用OP:


    $ b $


    如果表单为空,并且验证通过,为什么会显示绿色图像(validClass)?


    请参阅上文。一个字段只能是有效的或无效的。






    边注: >您可以使用或修改已作为部分包含的电话规则之一而不是数字长度规则 additional-methods.js 文件






    这是一个非常简单的解决方法, code>有效类,只要该字段不是必需的并保留空白。 (当这个字段在技术上是有效的时,这不是一个典型的行为来避免有效的类。)



    我已经分配了一个 class 称为可选到电话区域,并使用突出显示 unhighlight 回调函数如下...

      highlight:function(element,errorClass,validClass){
    $(element).addClass(errorClass).removeClass(validClass); ($(元素).hasClass('可选')&& $(元素).val())
    },
    unhighlight:function(element,errorClass,validClass){
    ==''){
    $(element).removeClass(errorClass).removeClass(validClass);
    } else {
    $(element).removeClass(errorClass).addClass(validClass);
    }
    },

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



    注意:如果表单中包含 radio 元素,它将无法正常工作。对于这种情况,请回顾插件的默认回调函数并进行必要的添加。


    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);
    });
    

    解决方案

    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.

    这篇关于验证jQuery插件,不需要字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆