如何在填写两个必填字段中的一个时验证表单 [英] How to validate form when only one out of two required fields is filled in

查看:358
本文介绍了如何在填写两个必填字段中的一个时验证表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个联系表单。它询问你的名字,然后询问你是否希望通过电话或电子邮件联系。电话和电子邮件字段是隐藏的,除非用户选择电话或电子邮件的单选按钮。一旦您点击电话或电子邮件,我会验证他们是否输入正确的电话或电子邮件地址。



我的问题是如何使用JQuery Validation进行检查,并在用户没有单击单选按钮时打印出错误消息?

解决方案

你只是问如何验证一组单选按钮?既然你没有显示任何代码,我可以告诉你的是如何验证一组 radio input '然后你可以使用 /Validation/rules#.22add.22rulesrel =nofollow>内置规则方法。再次,我需要在定制解决方案之前查看您的代码。



工作演示 http://jsfiddle.net/PbHwX/
$ b jQuery

  $(document).ready(function(){

$('#myform') .validate({
规则:{
radiotest:{
required:true
}
},
消息:{
radiotest:{
要求:请至少选择一个选项
}
}
});

});

HTML

 < input type =radioname =radiotestvalue =0/> 
< input type =radioname =radiotestvalue =1/>

文档 http://docs.jquery.com/Plugins/Validation


I have a contact form. It asks for your name and then it asks you whether you'd like to be contacted via telephone or email. The telephone and email fields are hidden unless the user selects a radio button for telephone or email. Once you click on either telephone or email I validate whether they input a correct telephone or email address.

My question is how to check with JQuery Validation and print out an error message if the user hasn't clicked on either radio button?

解决方案

Are you simply asking how to validate a set of radio buttons? Since you've shown no code, all I can show you is how you would validate a set of radio input's with the plugin.

Then you would dynamically add/remove rules from the corresponding inputs using the built-in rules method. Again, I'd need to see your code before customizing a solution.

Working Demo: http://jsfiddle.net/PbHwX/

jQuery:

$(document).ready(function () {

    $('#myform').validate({
        rules: {
            radiotest: {
                required: true
            }
        },
        messages: {
            radiotest: {
                required: "please select at least one option"
            }
        }
    });

});

HTML:

<input type="radio" name="radiotest" value="0" />
<input type="radio" name="radiotest" value="1" />

Documentation: http://docs.jquery.com/Plugins/Validation

这篇关于如何在填写两个必填字段中的一个时验证表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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