如何验证两个复选框并确保至少检查一个复选框?

时间:2018-04-23 15:38:00

标签: javascript jquery html5 html5-validation checkvalidity

我的表单中有两个复选框,所有其他表单字段都使用HTML5属性,因此我可以在提交时运行验证。这有点不同,因为我有两个复选框输入字段,我必须要求至少检查一个。这是一个例子:

$('.frm-Submit').on('submit', submitFrm);
function submitFrm(e){
    e.preventDefault(); // Prevnts default form submit.
    var $checkbox = $('.account-type');

    $checkbox.on('change', function(){
        var checked = false;
  
        $checkbox.each(function(){
           checked = checked || $(this).is(':checked')
        });
  
        $checkbox.prop('required', !checked)
    });

    console.log('Submit form.')
}
.form-group.required .control-label:after {
    content: " *";
    color: red;
}
<script language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script language="javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<form name="frmSave" id="frmSave" class="frm-Submit" autocomplete="off">
  <div class="form-group required">
    <label class="control-label" for="account"><span class="label label-primary">Account Type:</span></label>
    <div class="checkbox">
      <label for="user">
         <input type="checkbox" name="frm_isuser" id="frm_isuser" data-toggle="collapse" data-target="#user-account" required class="account-type"> <span class="label label-default">User</span>
      </label>
      <label for="staff">
         <input type="checkbox" name="frm_isstaff" id="frm_isstaff" data-toggle="collapse" data-target="#staff-account" required class="account-type"> <span class="label label-info">Staff</span>
      </label>
    </div>
  </div>
   <div class="row">
     <div class="form-group col-xs-12 col-sm-12 col-md-1 col-lg-1">
       <button type="submit" name="frm_submit" id="frm_submit" class="btn btn-primary">Submit</button>
     </div>
   </div> 
</form>

上面的示例抛出错误isUser.checkValidity()不是函数。有没有办法在复选框上运行有效性并至少进行两个必需/检查中的一个?

3 个答案:

答案 0 :(得分:2)

.is(":checked")已经返回boolean ...没有.checkValidity()方法。只是做:

if (isUser || isStaff) {
  //...code here if at least one is true
}

更新

在这种情况下,您需要的要求和验证基本上是两组独立的逻辑。

Constraint validation基于每个输入运行,因此您必须自己检查多个输入。

您可以选择通过侦听每个复选框上的事件来交换required参数的值...但由于它们似乎有不同的data-target,我认为更好的解决方案可能是只需使用选择表单类型。

答案 1 :(得分:2)

$("#frm_isuser").is(":checked")将返回一个显示是否已选中$("#frm_isuser")的布尔值。

checkValidity()是一种DOM方法,因此您应该使用document.getElementById("frm_isuser").checkValidity()$("#frm_isuser")[0].checkValidity()

修改:如果选中其中一个复选框,则将required属性设置为false两个。如果未选中任何一项,请将required设置为true

&#13;
&#13;
$('.frm-Submit').on('submit', submitFrm);

var $checkbox = $('.custom-class')

$checkbox.on('change', function(){
  var checked = false;
  
  $checkbox.each(function(){
    checked = checked || $(this).is(':checked')
  })
  
  $checkbox.prop('required', !checked)
})

function submitFrm(e) {
  e.preventDefault(); // Prevnts default form submit.
  
  console.log('Submit form.')
}
&#13;
.form-group.required .control-label:after {
  content: " *";
  color: red;
}
&#13;
<script language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script language="javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<form name="frmSave" id="frmSave" class="frm-Submit" autocomplete="off">
  <div class="form-group required">
    <label class="control-label" for="account"><span class="label label-primary">Account Type:</span></label>
    <div class="checkbox">
      <label for="user">
         <input type="checkbox" name="frm_isuser" id="frm_isuser" data-toggle="collapse" data-target="#user-account" required class="custom-class"> <span class="label label-default">User</span>
      </label>
      <label for="staff">
         <input type="checkbox" name="frm_isstaff" id="frm_isstaff" data-toggle="collapse" data-target="#staff-account" required class="custom-class"> <span class="label label-info">Staff</span>
      </label>
    </div>
  </div>
  <div class="row">
    <div class="form-group col-xs-12 col-sm-12 col-md-1 col-lg-1">
      <button type="submit" name="frm_submit" id="frm_submit" class="btn btn-primary">Submit</button>
    </div>
  </div>
</form>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

像这样添加,

$(function(){
	
	$('[type="checkbox"]').prop('required', true);
	$('[type="checkbox"]').filter('[required]').change(function(){
		$('[type="checkbox"]').prop('required', ($(this).is(':checked')) ? false : true);
	})
	$('.frm-Submit').on('submit', function(e){
        e.preventDefault(); // Prevnts default form submit.		
        if($('[type="checkbox"]:checked').length > 0){			
            console.log('Submit form.')
        }else{
			$(this).closest('form').get(0).checkValidity();
		}
    });
	
});
<script language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script language="javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<form name="frmSave" id="frmSave" class="frm-Submit" autocomplete="off">
  <div class="form-group required">
    <label class="control-label" for="account"><span class="label label-primary">Account Type:</span></label>
    <div class="checkbox">
      <label for="user">
         <input type="checkbox" name="frm_isuser" id="frm_isuser" data-toggle="collapse" data-target="#user-account"> <span class="label label-default">User</span>
      </label>
      <label for="staff">
         <input type="checkbox" name="frm_isstaff" id="frm_isstaff" data-toggle="collapse" data-target="#staff-account"> <span class="label label-info">Staff</span>
      </label>
    </div>
  </div>
   <div class="row">
     <div class="form-group col-xs-12 col-sm-12 col-md-1 col-lg-1">
       <button type="submit" name="frm_submit" id="frm_submit" class="btn btn-primary">Submit</button>
     </div>
   </div> 
</form>