用于显示输入错误AngularJS的表单验证指令 [英] AngularJS form validation directive for showing input errors

查看:186
本文介绍了用于显示输入错误AngularJS的表单验证指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个验证指令自动显示每个输入所有输入错误。
当用户键入此验证指令应显示在当前时刻和错误列表中的所有错误都应该自动更新。

I need to create a validation directive for showing all input errors for each input automatically. This validation directive should show all errors at current moment and list of errors should be updated automatically while user is typing.

我需要显示所有的错误输入,如果输入的是脏的,不是空的,无效的。我需要把所有的错误加入到HTML元素此输入元件附近。

I need to show all errors for input if input is dirty, not empty and invalid. I need to add all errors into html element near this input element.

例如,如果输入有TYPE =电子邮件和NG-MINLENGTH个=5,用户键入'ABC'我需要显示接近这个输入这样的错误:电子邮件地址无效;请输入至少5个字符;

For example if input have type="email" and ng-minlength="5" and user typed 'abc' I need to show such errors near this input: 'Invalid email; Please enter at least 5 characters;'

例如,如果输入的类型为类型化的'100'我需要表现出接近这个这样的错误=号ATTR和最小=200和最小模型=minnumber和minnumber模式设置为'300'和用户输入:'请输入500的最小数目;应小于最小数量越大;

For example if input has type="number" attr and min="200" and min-model="minnumber" and minnumber model set to '300' and user typed '100' I need to show such errors near this input: 'Please enter the minimum number of 500; Should be greater than Min Number;'

此外,我需要的,如果相关的模型(最小模型参数)被更新来更新$ P $光伏例如输入所有错误消息。

Also I need to update all errors messages for input in prev example if related model (min-model param) is updated.

var app = angular.module('app', []);

app.controller('appCtrl', function ($scope) {

});

app.directive('validate', function () {
    return {
        restrict: 'A',
        require: 'ngModel', // require:  '^form',

        link: function (scope, element, attrs, ctrl) {
            console.log('======================');
            console.log(scope);
            console.log(element);
            console.log(attrs);
            console.log(ctrl);
            console.log(scope.form.$error);
            angular.forEach(scope.form.$error, function (value, key) {
                console.log('scope.form.$error = ' + key + ': ' + value);
                console.log(value);
            });

        }
    };
});


app.directive('positiveInteger', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ctrl) {
            ctrl.$parsers.unshift(function (viewValue) {
                var INTEGER_REGEXP = /^\d+$/;
                if (INTEGER_REGEXP.test(viewValue)) { // it is valid
                    ctrl.$setValidity('positiveInteger', true);
                    return viewValue;
                } else { // it is invalid, return undefined (no model update)
                    ctrl.$setValidity('positiveInteger', false);
                    return undefined;
                }
            });
        }
    };
});


app.directive('positiveFloat', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ctrl) {
            ctrl.$parsers.unshift(function (viewValue) {
                var FLOAT_REGEXP = /^(?:[1-9]\d*|0)?(?:\.\d+)?$/;
                if (FLOAT_REGEXP.test(viewValue)) { // it is valid
                    ctrl.$setValidity('positiveInteger', true);
                    return viewValue;
                } else { // it is invalid, return undefined (no model update)
                    ctrl.$setValidity('positiveInteger', false);
                    return undefined;
                }
            });
        }
    };
});


app.directive('minModel', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ctrl) {
            ctrl.$parsers.unshift(function (viewValue) {
                if (viewValue > scope[attrs.minModel]) { // it is valid
                    ctrl.$setValidity('minModel', true);
                    return viewValue;
                } else { // it is invalid, return undefined (no model update)
                    ctrl.$setValidity('minModel', false);
                    return undefined;
                }
            });

        }
    };
});

你能帮助使这个验证指令?

或者你可以点我到正确的方向?

链接到的jsfiddle一些code测试

P.S。同样的事情也与 UI-utils的制作但他们的指令不给在一个地方设置类似的错误消息的能力

P.S. Something similar is made with UI-Utils but their directive does not give ability to set similar error messages in one place.

推荐答案

看看在 NG的消息directive 。它相当优雅。例如:

Take a look at the ng-messages directive. Its fairly elegant. Example:

<form name="myForm">
  <input type="text" ng-model="field" name="myField" required minlength="5" />
  <div ng-messages="myForm.myField.$error">
    <div ng-message="required">You did not enter a field</div>
    <div ng-message="minlength">The value entered is too short</div>
  </div>
</form>

您可以再与任何形式的验证结合起来。只需把从验证到的元素$错误对象的错误信息和它们在UI自动呈现。

You can then combine it with any form validation. Just place the error messages from the validators onto the elements $error object and they are automatically rendered in your UI.

这篇关于用于显示输入错误AngularJS的表单验证指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆