为什么验证工作在表单名而不是模型上

Why does validation work on form names rather than on the model?

本文关键字:模型 验证 工作 表单 为什么      更新时间:2023-09-26

考虑以下代码:

<form class="form-horizontal" name="accountForm">
    <div class="form-group" ng-class="{ 'has-error': accountForm.CurrentPassword.$invalid  }">
        <label class="col-sm-2 control-label">Current Password:</label>
        <div class="col-sm-10">
            <input class="form-control" type="password" name="CurrentPassword" ng-model="user.CurrentPassword" ng-minlength="8" placeholder="Enter current password">
        </div>
    </div>
</form>

为什么我们必须给表单和输入字段一个名称,并对其执行验证,是否有一种方法直接使用ng-model ?如果我们能做到:

ng-class="{ 'has-error': user.CurrentPassword.$invalid  }"> 

不要把它放在一个字段的上下文中,而是放在有几十个字段的表单上下文中。它很快就开始变老。在我看来

<input name="CurrentPassword" ng-model="user.CurrentPassword"/>

是多余的(尽管我知道这涉及到不同的功能,其中一个来自传统的HTML post方法)。然而,我在Angular中发布了我的模型,所以我不需要那个功能,但由于验证,我被迫添加它?

编辑:

是的,当然修改类和/或使用基于模型的disabled=""也是一种选择,但结果是非常丑陋的HTML,显然$touched, $invalid$error将不起作用…还有其他选择吗?或者有人能解释一下为什么这样写有什么合理的理由吗?

如果你想使用AngularJS表单验证,你必须像以前那样使用它。否则,您可以根据模型绑定执行自己的规则,例如:

<form class="form-horizontal" name="accountForm">
        <div class="form-group" ng-class="{ 'has-error': (user.CurrentPassword.length < 8)  }">
            <label class="col-sm-2 control-label">Current Password:</label>
            <div class="col-sm-10">
                <input class="form-control" type="password" name="CurrentPassword" ng-model="user.CurrentPassword" placeholder="Enter current password">
            </div>
        </div>
</form>