jQuery条件字段验证(必须填写两个字段中的至少一个)

时间:2014-05-17 00:46:24

标签: jquery forms validation

http://jsfiddle.net/sarah97302/8LRt4/2/

我甚至无法测试是否在jsfiddle中有效,因为我在尝试提交表单时不断收到错误消息:

{"error": "Shell form does not validate{'html_initial_name': u'initial-js_lib', 'form': <mooshell.forms.ShellForm object at 0x3ff9310>, 'html_name': 'js_lib', 'html_initial_id': u'initial-id_js_lib', 'label': u'Js lib', 'field': <django.forms.models.ModelChoiceField object at 0x3ff82d0>, 'help_text': '', 'name': 'js_lib'}{'html_initial_name': u'initial-js_wrap', 'form': <mooshell.forms.ShellForm object at 0x3ff9310>, 'html_name': 'js_wrap', 'html_initial_id': u'initial-id_js_wrap', 'label': u'Js wrap', 'field': <django.forms.fields.TypedChoiceField object at 0x3ff8390>, 'help_text': '', 'name': 'js_wrap'}"}

我环顾四周并根据其他问题看起来错误消息意味着我需要以某种方式禁用表单提交但我不知道该怎么做并仍然测试验证功能?

如果我尝试在没有填写两个字段中的至少一个(出生日期或PIN)的情况下提交,我希望显示一条警告消息。

function Validate() {
if ( $( "#custom-105959", "#custom-105976").val() === "") 
  {
alert( "You must enter either your date of birth or your Personal Identification Number (PIN) ." );
$( "#custom-105959").focus();
      event.preventDefault(); }

 }

$('#signup').submit(Validate);

和html:

<form id="signup" method="post" action="">
<div><label >Name</label>
        <input  id="custom-105958"  name="custom-105958" type="text"></div>
    <div><label >Birthday (mm/dd/yy)</label>
        <input  id="custom-105959"  name="custom-105959" type="text"></div>

    <div><label >Personal Identification Number (PIN)</label>
        <input  id="custom-105976" name="custom-105976" type="text">  </div>    
    <input type="submit" value="Submit" />


</form>

1 个答案:

答案 0 :(得分:1)

修改

function Validate() {
    var customfirst = document.getElementById('custom-105959').value;
    var customsecond = document.getElementById('custom-105976').value;
    if (customfirst == '' && customsecond == ''){
        alert('empty');   
    }
    else {
        alert('inserted');   
    }
}

http://jsfiddle.net/8LRt4/4/