如何减少AngularJS中的表单验证字段

时间:2015-06-14 18:22:11

标签: javascript angularjs forms validation

我有一个包含3个输入字段的表单。但是我也希望将表单用于其他页面。因此我减少了形式。一开始我将视图定义如下:

查看:

<form class="form-horizontal" name="editForm" novalidate>
  <div ng-repeat="elements in form">
    <div class="form-group-sm has-feedback" ng-repeat="el in elements.items" ng-class="{ 'has-error' : hasError(editForm), 'has-success' : hasSuccess(editForm) }">
       <label class="control-label" for="{{el.id}}">{{el.label}}</label>
       <input type="{{el.fieldType}}"
              class="form-control" 
              placeholder="{{el.label}}"  
              name="{{el.name}}" 
              id="{{el.id}}"
              ng-model="selected[el.model]" 
              ng-disabled="{{el.disabled}}"
              ng-pattern="el.pattern" 
              ng-required="{{el.required}}"
       />
       <p class="help-block" ng-show="editForm.{{el.name}}.$error.required && editForm.{{el.name}}.$touched">Field is required.</p>
       <p class="help-block" ng-show="editForm.{{el.name}}.$error.pattern">Thats the pattern error message.</p>
   </div>
 </div>    
</form>

我想在函数中外包错误消息/验证。 p-Tag中的错误消息不起作用。

我在Ctrl中尝试了这个:

$scope.hasError = function (form) {
   return form.Firstname.$invalid && form.Firstname.$dirty;
}

$scope.hasSuccess = function (form) {
   return form.Firstname.$valid;
}

这仅适用于输入字段名字。但是,如何为所有字段(名字,姓氏,年龄)动态定义它?

2 个答案:

答案 0 :(得分:1)

将动态字段名称传递给函数:

ng-class="{ 'has-error' : hasError(editForm, el.name), 'has-success' : hasSuccess(editForm, el.name) }"

并在控制器中使用括号表示法来访问变量ngModelController:

$scope.hasError = function (form, name) {
   return form[name].$invalid && form[name].$dirty;
};

$scope.hasSuccess = function (form, name) {
   return form[name].$valid;
};

答案 1 :(得分:1)

试试这个

 <p class="help-block" ng-show="editForm[el.name].$error.required && editForm[el.name].$touched">Field is required.</p>
 <p class="help-block" ng-show="editForm[el.name].$error.pattern">Thats the pattern error message.</p>