【问题标题】:checkbox validation is not working as expected复选框验证未按预期工作
【发布时间】:2018-03-20 04:02:10
【问题描述】:

我想在用户使用 bootstrap 和 angularjs 单击提交按钮时验证表单。如果表单中的任何字段为空白,我想在空白元素下方显示错误消息。

演示:https://plnkr.co/edit/55lFImusbCznYjLXypDu?p=preview

html代码:

<form name="myForm" ng-controller="ExampleController">
   <div>Select Color : </div>
      <label name="team" ng-repeat="color in colorNames" class="checkbox-inline">
                        <input type="checkbox" name="color" value="{{color}}" ng-checked="selectedColor.indexOf(color) > -1" ng-click="userSelection(color)"> {{color}}
                  <br>  </label><br>
                <div ng-show="myForm.$submitted || myForm.color.$touched">
                    <p class="error-mesg" ng-show="headerForm.color.$error.required">Select the color</p>
                </div>
            <div class="">
                <div style="color: black;">Username : </div>
               <input type="text" name="user" value="" required>
                <div ng-show="myForm.$submitted || myForm.user.$touched">
                    <p class="error-mesg" ng-show="myForm.user.$error.required">The Username is required</p>
                </div>
            </div>
             <button type="submit" class="btn btn-primary" ng-click="submitForm(myForm)">Submit</button>
 </form>

我上面的代码在未选中时无法在复选框下方显示错误消息。当用户单击提交按钮而不选择至少一个复选框时,我想在复选框下方显示错误消息“请选择颜色”。当用户单击任何复选框,错误消息应该会消失。

【问题讨论】:

    标签: html angularjs twitter-bootstrap


    【解决方案1】:

    您可以动态添加复选框输入所需的:ng-required="selectedColor.length === 0"

    if you do not select color, checkboxs will be required, when color is selected, then is it unrequired.

    <input ng-required="selectedColor.length === 0" oninvalid="this.setCustomValidity('Please select the color')" type="checkbox" name="color" value="{{color}}" ng-checked="selectedColor.indexOf(color) > -1" ng-click="userSelection(color)">
    

    【讨论】:

    • ng-model="user" 也缺少用户输入。
    • 我想在复选框下方显示我给出的错误消息“请选择颜色”。使用您建议的代码plnkr.co/edit/qteeuHzdfCeOufRTZI83?p=preview 它通过指向第一个复选框显示“如果您想继续,请选中此框”。
    • @dexter:实际上您没有在 2 个输入字段上使用 ng-model,$scope.myForm.$valid 始终为 true。
    • 您可以使用 oninvalid 属性 (html5) 更改文本。他可以使用 ngChecked 指令代替 ngModel。
    • @JonathanAnctil - 我添加了 ng-model 但它仍然没有重新调整我的自定义错误消息 'Please select the color' 。更新链接plnkr.co/edit/xRJiBjh4mQqr0lpPn15x?p=preview
    猜你喜欢
    • 2012-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-21
    • 1970-01-01
    • 2019-09-24
    • 1970-01-01
    • 2018-01-27
    相关资源
    最近更新 更多