繁体   English   中英

Angular JS - 如何将表单验证作为全局服务? 最佳实践

[英]Angular JS - How to make form validation as global service? Best practice

我的Angular应用程序中有一些数据验证表单。 所有表单包含如下相同的验证消息:

 <span class="formValidationError" ng-show="myForm.customViewName.$error.required">Required!</span><br>
                    <span class="formValidationError" ng-show="myForm.customViewName.$error.minlength">Too short!</span>
                    <span class="formValidationError" ng-show="myForm.customViewName.$error.maxlength">Too long!</span>
                    <span class="formValidationSuccess" ng-show="myForm.$valid">Data valid</span>

我想让我的表单更容易维护。

是否可以将此验证消息作为全局服务,指令或类似的东西?

我的表单看起来像这样:

<div class="modal fade">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                <h4 class="modal-title">Add name of custom view</h4>
            </div>
            <form name="myForm">
            <div class="modal-body">
                    <input type="text" name="customViewName" ng-model="customView.name" class="form-control" ng-minlength="5" ng-maxlength="10" required>
                    <span class="formValidationError" ng-show="myForm.customViewName.$error.required">Required!</span><br>
                    <span class="formValidationError" ng-show="myForm.customViewName.$error.minlength">Too short!</span>
                    <span class="formValidationError" ng-show="myForm.customViewName.$error.maxlength">Too long!</span>
                    <span class="formValidationSuccess" ng-show="myForm.$valid">Data valid</span>
            </div>
            <div class="modal-footer">
                <button type="button"  class="btn btn-default" data-dismiss="modal">Cancel</button>
                <button type="button" ng-controller="UsersCtrl" ng-disabled="!myForm.$valid" ng-click="saveCustomView()" class="btn btn-primary">Save</button>
            </div>
            </form>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

可以请有人为此推荐一些好的解决方案吗?

谢谢你的建议。

这个问题可能很旧,但你一定要看看我的Angular-Validation Directive / Service 我厌倦了用AngularJS建议我们的方式一遍又一遍地重复代码。 所以我决定构建自己的库进行验证。

它有很多功能,很容易使用,你会笑。 举个例子,你只需要输入并添加一个新的属性

<input ... validation="min_length:5|max_length:10|required" />

你完成了! 该库负责其余部分,有超过50种验证器类型,它们都有定义的通用错误消息(也有7种不同的语言环境)。 如果默认验证器不够,您还可以轻松定义自定义正则表达式模式。

所以你不能比这更简单... 1行代码,或者我应该说,在你的输入中添加1个新属性,瞧!

让我们举一个更大的例子,使用默认的AngularJS验证表单的方式如下:

<input type="text" name="username" ng-model="user.username" ng-minlength="3" ng-maxlength="8" required />
<div ng-show="form.$submitted || form.user.$touched">
  <span ng-show="userForm.username.$error.minlength" class="help-block">Username is too short.</p>
  <span ng-show="userForm.username.$error.maxlength" class="help-block">Username is too long.</p>
</div>
<input type="text" name="firstname" ng-model="user.firstname" ng-minlength="3" ng-maxlength="50" required />
<div ng-show="form.$submitted || form.user.$touched">
  <span ng-show="userForm.firstname.$error.minlength" class="help-block">Firstname is too short.</p>
  <span ng-show="userForm.firstname.$error.maxlength" class="help-block">Firstname is too long.</p>
</div>
<input type="text" name="lastname" ng-model="user.lastname" ng-minlength="2" ng-maxlength="50" required />
<div ng-show="form.$submitted || form.user.$touched">
  <span ng-show="userForm.lastname.$error.minlength" class="help-block">Lastname is too short.</p>
  <span ng-show="userForm.lastname.$error.maxlength" class="help-block">Lastname is too long.</p>
</div>

通过我的Angular-Validation它很简单:

<input type="text" name="username" ng-model="user.username" validation="min_len:3|max_len:8|required"  />
<input type="text" name="firstname" ng-model="user.firstname" validation="alpha_dash|min_len:3|max_len:50|required"  />
<input type="text" name="lastname" ng-model="user.lastname" validation="alpha_dash|min_len:2|max_len:50|required"  />

3输入= 3行代码。 这是应该的方式和它应该保持的方式。 简单是关键。

可在BowerNuGet (在angular-validation-ghiscoding的标记名下)。 所以请查看我的库Angular-ValidationPLUNKER的现场演示。

它加载了功能(自定义正则表达式验证器,AJAX远程验证,验证摘要,备用文本错误,与服务一起动态验证等)。 因此,请务必检查Wiki文档 ......最后,使用Protractor(超过1500个断言)对其进行全面测试,因此不要害怕在生产中使用。

请注意,我是这个图书馆的作者

从我们这边来看,我们遇到了类似的问题,我们决定实施ValidationSummary指令:

http://lemoncode.github.io/lc-validation-summary/

https://github.com/Lemoncode/lc-validation-summary

使用此方法,您可以将所有错误消息集中在一个入口点(例如,在给定的提供程序中配置它们)。 它正在等待实现SingleFieldSummary指令。

这是我为此任务编写的指令。 看看我如何使用它:

<input type="text" name="customViewName" ng-model="customView.name" class="form-control" ng-minlength="5" ng-maxlength="10" required="" />
<div validate-error="customViewName">
    <span class="required">Required!</span>
    <span class="minlength">Too short!</span>
    <span class="maxlength">Too long!</span>
</div>

这是指令的代码:

angular.module('directives.validation', []).directive('validateError', function () {
    return {
        restrict: 'AM',
        require: '^form',
        link: function (scope, element, attrs, formController) {

            function validate() {

                if (formController.$dirty) {

                    $formGroup.toggleClass('has-error', ngModelController.$invalid);

                    if (showErrorMessages) {
                        var errors = element[0].children;
                        if (errors.length > 1) {
                            for (var i = 0; i < errors.length; i++) {
                                angular.element(errors[i]).toggle(ngModelController.$error[errors[i].className]);
                            }
                        }
                        element.toggle(ngModelController.$invalid);
                    }
                }
            }

            /** @property validateError */
            var $formGroup = element.closest('.form-group'),
                showErrorMessages = element[0].nodeType === 1,
                ngModelController = formController[attrs.validateError];

            scope.$watch(function () {
                return ngModelController.$error;
            }, validate, true);

            scope.$watch(function () {
                return formController.$pristine;
            }, function (newVal, oldVal) {
                if (newVal !== oldVal) {
                    validate();
                }
            });
        }
    };
});

最初使用此CSS隐藏所有错误:

[validate-error] {
    display: none;
    color: #A94442;
}

演示: http//plnkr.co/edit/dLvBUGH2Q4peddbizxqV?p = preview

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM