Atleast使用angularjs在表单验证中选中一个复选框

时间:2017-06-20 11:38:38

标签: javascript html angularjs

这是我的HTML

<form name="sales">
<div class="sale-type">
                            <p>Which would you like to sell?</p>
                            <fieldset class="md-form form-group">
                                <input ng-model="art.originalForSale" name="originalForSale" type="checkbox" class="filled-in" id="checkbox2">
                                <label for="checkbox2">My Original ART</label>
                            </fieldset>

                            <fieldset class="md-form form-group">
                                <input ng-model="art.printForSale" name="printForSale" type="checkbox" class="filled-in" id="checkbox22">
                                <label for="checkbox22">Prints of my ART</label>
                            </fieldset>
                        </div>
<button type="submit" ng-disabled="sales.$invalid" class="btn-form btn-next c-sprite" alt="Submit"></button>
</form>

我想显示验证消息,显示至少需要一个复选框,我该怎么办

找到了这个问题的解决方案How to require at least 1 checkbox for AngularJS Form Validation?

但它使用的脚本我想要一个不使用scirpt的解决方案

目前我正在使用

<span  ng-show="part1.originalForSale.$error.required" class="error">Checkbox required</span>

4 个答案:

答案 0 :(得分:1)

I think that solve your problem:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
<ng-form name="sales" ng-app >
  <div class="sale-type">
    <p>Which would you like to sell?</p>
    <fieldset class="md-form form-group">
      <input ng-model="art.originalForSale"  value="cb1" name="originalForSale" type="checkbox" class="filled-in" id="checkbox2" ng-required="!art.printForSale">
      <label for="checkbox2">My Original ART</label>
    </fieldset>

    <fieldset class="md-form form-group">
      <input ng-model="art.printForSale" value="cb2" name="printForSale" type="checkbox" class="filled-in" id="checkbox22" ng-required="!art.originalForSale">
      <label for="checkbox22">Prints of my ART</label>
    </fieldset>
  </div>
  <span  ng-show="sales.$invalid" class="error">Checkbox required</span>
  <button type="submit" ng-disabled="sales.$invalid" class="btn-form btn-next c-sprite" alt="Submit"></button>
</ng-form>

答案 1 :(得分:0)

您可以使用ngRequired指令。有一个简单的例子。

<input name="checkbox1" type="checkbox" ng-model="isChecked1" ng-required="isChecked2">
<input name="checkbox2" type="checkbox" ng-model="isChecked2" ng-required="isChecked1">

您可以使用ngMessages作为验证消息

<div ng-messages="myForm.checkbox1.$error || myForm.checkbox2.$error" style="color:maroon" role="alert">
    <div ng-message="required">You did not select a checkbox !</div>
</div>

答案 2 :(得分:0)

你在下面试过吗?

<span  ng-show="!(art.printForSale || art.originalForSale) " class="error">Checkbox required</span>

如果您想在提交表单后显示消息,请使用$ dirty。

答案 3 :(得分:-1)

在输入标记中写入必需的属性以显示msg

    <span ng-show="frmRegister.name.$dirty && frmRegister.name.$error.">this is req...</span>