AngularJS中的表单验证摘要,每个字段包含自定义消息

时间:2021-12-07 07:11:03

I'm trying to render a validation summary on a page using AngularJS. Here's what I have so far:

我正在尝试使用AngularJS在页面上呈现验证摘要。这是我到目前为止所拥有的:

<div ng-app>
    <div ng-controller="ctrl">
        <form name="userForm">
            <fieldset>
                <legend>User Info</legend>
                <p><label>Name: <input type="text" required ng-maxlength="15" name="name" ng-model="name" /></label></p>
                <p><label>Age: <input type="number" required name="age" ng-model="age" /></label></p>
                <p><label>Favorite Color: <input type="text" required name="favColor" ng-model="favColor" /></label></p>
                <p><input type="button" value="Submit" ng-click="submitForm()" /></p>
            </fieldset>
        </form>
        <div id="validationSummary" ng-show="hasValidationErrors()">
            <ul>
                <li ng-repeat="error in validationErrors">{{ error }}</li>
            </ul>
        </div>
    </div>
</div>

In my controller, I'm creating an array with all of the errors.

在我的控制器中,我正在创建一个包含所有错误的数组。

function ctrl($scope) {

    $scope.hasValidationErrors = function () {
        return $scope.validationErrors && $scope.validationErrors.length > 0;
    };

    $scope.submitForm = function() {
        $scope.validationErrors = [];

        for (var property in $scope.userForm) {
            if ($scope.userForm.hasOwnProperty(property) && $scope.userForm[property].$invalid) {
                $scope.validationErrors.push($scope.userForm[property].$name);
            }
        }
    }
}

The thing I can't figure out is: how can I get more than just the name of each field that is invalid? I've noticed that there is also an $error property on each field. Outputting this instead of $name gives me the following:

我无法弄清楚的是:我怎么能得到的不仅仅是每个无效字段的名称?我注意到每个字段上还有一个$ error属性。输出这个而不是$ name给我以下内容:

{"required":true,"maxlength":false}
{"required":true,"number":false}
{"required":true}

So I can get the field name, and I can get an object that describes what is wrong with that particular field. How can I define an error message, so that if a field is required it will output "{name} is required"? It seems like this could be a data- attribute on the input element itself, although I don't know how I would access that attribute.

所以我可以得到字段名称,我可以得到一个描述该特定字段错误的对象。如何定义错误消息,以便在需要字段时输出“{name} is required”?看起来这可能是输入元素本身的数据属性,虽然我不知道如何访问该属性。

Of course, it's also possible that I'm making things entirely too difficult on myself. Is there a better way to approach this while staying in the "AngularJS" world?

当然,也有可能我自己制造的东西太难了。在“AngularJS”世界中有没有更好的方法来解决这个问题?

Here's a link to the jsFiddle I've been working on.

这是我一直在努力的jsFiddle的链接。

3 个解决方案

#1


2  

A far easier and cleaner way is demonstrated here

这里展示了一种更简单,更清洁的方式

Simply put (where form1 is your form name attribute):

简单地说(form1是你的表单名称属性):

<ul>
  <li ng-repeat="(key, errors) in form1.$error track by $index"> <strong>{{ key }}</strong> errors
    <ul>
      <li ng-repeat="e in errors">{{ e.$name }} has an error: <strong>{{ key }}</strong>.</li>
    </ul>
  </li>
</ul>

#2


1  

A totally dynamic validation summary based on AngularJS 1.5.7 with ngMessages using field names that the user recognizes

基于AngularJS 1.5.7的完全动态验证摘要,其中ngMessages使用用户可识别的字段名称

A template with error messages:

带有错误消息的模板:

<script type="text/ng-template" id="error-messages">
  <span ng-message="required">This field is required.</span>
  <span ng-message="email">Please enter a valid email.</span>
</script>

Display of the error summary (here for a form named "candidateForm"):

显示错误摘要(此处为名为“candidateForm”的表单):

      <div data-ng-if="candidateForm.$submitted && candidateForm.$invalid">            
          Please correct these fields and then try to send again:
          <ul>
            <li data-ng-repeat="field in candidateForm" data-ng-if="candidateForm[field.$name].$invalid">
              <div>
                {{ getValFieldName(field) }}
                <span data-ng-messages="candidateForm[field.$name].$error" role="alert">
                  <span data-ng-messages-include="error-messages"></span>
                </span>
              </div>
            </li>
          </ul>
      </div>

A helper function to get the name of the label associated with the input field (instead of displaying input field names or "internal ID codes" to users):

一个辅助函数,用于获取与输入字段关联的标签的名称(而不是向用户显示输入字段名称或“内部ID代码”):

$scope.getValFieldName = function (field) {
  return $("label[for=" + field.$name + "]").text(); // to get label associated with input field
  // return $("#" + field.$name).attr("placeholder"); // to get placeholder of input field
};

You can reuse this set of standard error messages on multiple forms, ngMessages ensure only one error displayed per field, and looks like the fields are listed in the order they appear in the HTML.

您可以在多个表单上重复使用这组标准错误消息,ngMessages确保每个字段只显示一个错误,看起来这些字段按照它们在HTML中的显示顺序列出。

Should probably be made into a directive instead of the jQuery-style helper function, and might even want to add a click-handler on each error message to scroll to the input field with the error. Maybe another will run with that idea?

应该可以将其变成一个指令而不是jQuery样式的帮助函数,甚至可能希望在每个错误消息上添加一个click-handler来滚动到带有错误的输入字段。也许另一个会与这个想法一起运行?

#3


-1  

Use below line to get values of every text box

使用下面的行来获取每个文本框的值

var value = $scope.userForm[property].$name;
var vl =$('*[name="' + value + '"]').data('required-message')
$scope.validationErrors.push(vl);

#1


2  

A far easier and cleaner way is demonstrated here

这里展示了一种更简单,更清洁的方式

Simply put (where form1 is your form name attribute):

简单地说(form1是你的表单名称属性):

<ul>
  <li ng-repeat="(key, errors) in form1.$error track by $index"> <strong>{{ key }}</strong> errors
    <ul>
      <li ng-repeat="e in errors">{{ e.$name }} has an error: <strong>{{ key }}</strong>.</li>
    </ul>
  </li>
</ul>

#2


1  

A totally dynamic validation summary based on AngularJS 1.5.7 with ngMessages using field names that the user recognizes

基于AngularJS 1.5.7的完全动态验证摘要,其中ngMessages使用用户可识别的字段名称

A template with error messages:

带有错误消息的模板:

<script type="text/ng-template" id="error-messages">
  <span ng-message="required">This field is required.</span>
  <span ng-message="email">Please enter a valid email.</span>
</script>

Display of the error summary (here for a form named "candidateForm"):

显示错误摘要(此处为名为“candidateForm”的表单):

      <div data-ng-if="candidateForm.$submitted && candidateForm.$invalid">            
          Please correct these fields and then try to send again:
          <ul>
            <li data-ng-repeat="field in candidateForm" data-ng-if="candidateForm[field.$name].$invalid">
              <div>
                {{ getValFieldName(field) }}
                <span data-ng-messages="candidateForm[field.$name].$error" role="alert">
                  <span data-ng-messages-include="error-messages"></span>
                </span>
              </div>
            </li>
          </ul>
      </div>

A helper function to get the name of the label associated with the input field (instead of displaying input field names or "internal ID codes" to users):

一个辅助函数,用于获取与输入字段关联的标签的名称(而不是向用户显示输入字段名称或“内部ID代码”):

$scope.getValFieldName = function (field) {
  return $("label[for=" + field.$name + "]").text(); // to get label associated with input field
  // return $("#" + field.$name).attr("placeholder"); // to get placeholder of input field
};

You can reuse this set of standard error messages on multiple forms, ngMessages ensure only one error displayed per field, and looks like the fields are listed in the order they appear in the HTML.

您可以在多个表单上重复使用这组标准错误消息,ngMessages确保每个字段只显示一个错误,看起来这些字段按照它们在HTML中的显示顺序列出。

Should probably be made into a directive instead of the jQuery-style helper function, and might even want to add a click-handler on each error message to scroll to the input field with the error. Maybe another will run with that idea?

应该可以将其变成一个指令而不是jQuery样式的帮助函数,甚至可能希望在每个错误消息上添加一个click-handler来滚动到带有错误的输入字段。也许另一个会与这个想法一起运行?

#3


-1  

Use below line to get values of every text box

使用下面的行来获取每个文本框的值

var value = $scope.userForm[property].$name;
var vl =$('*[name="' + value + '"]').data('required-message')
$scope.validationErrors.push(vl);