jQuery验证插件,phoneUS字段已断开形式 [英] jQuery Validation Plugin, phoneUS field is breaking form

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

问题描述

我一直在使用jquery验证插件在浏览器端进行验证的一种简单形式,由于某种我不知道的原因,似乎"phoneUS"规则似乎正在破坏其余的验证代码.

I've been working on a simple form using the jquery validation plugin for browser-side validating, and for some reason unbeknownst to me it seems like the 'phoneUS' rule seems to be breaking the rest of the validation code.

只要表单上的该字段("tel")为空白,验证就可以正常进行.但是,如果在电话字段中输入了任何内容(包括字母),那么即使其他必填字段留为空白,也将跳过验证并提交表单.但是,如果从代码中删除了"phoneUS"规则,则仍将应用应用于"tel"输入的其他验证规则.不用说,我很困惑.

So long as that field ("tel") is blank on the form, the validation works as intended. But if anything is entered into the telephone field (including letters), then the validation is skipped and the form is submitted, even if other required fields are left blank. However, if the 'phoneUS' rule is taken out of the code, other validation rules applied to the 'tel' input still apply. Needless to say, I'm thoroughly confused.

脚本为:

<script type="text/javascript">
$(document).ready(function(){
$('#survey1').validate({
    rules: {
    firstname: {
            required: true,
            },      

    lastname: {
            required: true
            },

    address1: {
            required: true
            },

    city: {
            required: true
            },      

    state: {
            required: true
            },  

    zip: {
            required: true,
            digits: true
            },  

    tel: {
            required: true,
            phoneUS: true
            },  

    email: {
            email: true
            }

   }



   });
});

</script>

标签和输入字段只是名称与脚本匹配的简单文本框.表单操作设置为使用php文件将结果通过电子邮件发送到静态电子邮件地址.如果有任何其他信息会有所帮助,我会提供.

the labels and input fields are just simple text boxes with names matching the script. The form action is set to use a php file to email the results to a static e-mail address. If any other information would be helpful, I'll provide it.

我对jQuery相对较新,因此随时提供指针(多余的字符等).

I'm relatively new to jQuery, so feel free to offer pointers (superfluous characters, etc.).

谢谢!

推荐答案

jQuery Validate不附带phoneUS函数标准;您必须添加它.在您的$('#survey1').validate()代码之前,请调用以下函数:

jQuery Validate does not come with the phoneUS function standard; you have to add it. Before your $('#survey1').validate() code, call this function:

// Add US Phone Validation
jQuery.validator.addMethod('phoneUS', function(phone_number, element) {
    phone_number = phone_number.replace(/\s+/g, ''); 
    return this.optional(element) || phone_number.length > 9 &&
        phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, 'Please enter a valid phone number.');

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

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