【问题标题】:AngularJS, issue on form validationAngularJS,表单验证问题
【发布时间】:2016-02-08 10:58:56
【问题描述】:

我有一个表单,用户需要输入 2 次电子邮件。 我在互联网上(但无法再找到链接)找到了一些我想要的角度代码。 唯一的问题是当两封电子邮件相同时,一个输入仍然得到类

.ng-invalid.ng-脏

所以我无法提交表单。

我的代码如下:

css:

.ng-invalid.ng-dirty{
    border-color: #FA787E;
}

.ng-valid.ng-dirty{
    border-color: #78FA89;
}

html:

 <div ng-app="myApp">
      <form name="formTemplate" novalidate>
        <input id="email1" type="email" ng-model="currentForm.email1" name="email1" required>
        <span ng-show="formTemplate.email1.$error.required && formTemplate.email1.$dirty">required</span>
        <span ng-show="!formTemplate.email1.$error.required && formTemplate.email1.$error.email1 && formTemplate.email1.$dirty">invalid email</span>  
        <input id="email2" type="email" name="email2" ng-model="currentForm.email2" same-email required>
        <span ng-show="formTemplate.email2.$error.required && formTemplate.email2.$dirty">Please confirm your email.</span>
        <span ng-show="!formTemplate.email2.$error.required && formTemplate.email2.$error.noMatch && formTemplate.email1.$dirty">Emails do not match.</span>
      </form>
    </div>

javascript:

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

angular.module('UserValidation', []).directive('sameEmail', function () {
    return {
        require: 'ngModel',
        link: function (scope, elm, attrs, ctrl) {
            ctrl.$parsers.unshift(function (viewValue, $scope) {
                var noMatch = viewValue != scope.formTemplate.email1.$viewValue;
                ctrl.$setValidity('noMatch', !noMatch)
            })
        }
    }
})

这里有一个 jsfiddle:http://jsfiddle.net/malamine_kebe/pq6fw04v/

【问题讨论】:

  • 我想你已经在验证了。这样会显示消息电子邮件不匹配

标签: angularjs forms validation formvalidation-plugin


【解决方案1】:

更新你的jsfiddle。您不会从 ctrl.$parsers.unshift 返回值。

ctrl.$parsers.unshift(function (viewValue, $scope) {
            var noMatch = viewValue != scope.formTemplate.email1.$viewValue;
            ctrl.$setValidity('noMatch', !noMatch);
            return noMatch;
        })

更新的 jsfiddle

【讨论】:

  • 感谢您的帮助,但现在它不检查两封电子邮件是否相同
  • 支票。请检查jsfiddle
猜你喜欢
  • 2015-10-09
  • 2014-11-23
  • 2014-08-16
  • 2016-07-06
  • 1970-01-01
  • 1970-01-01
  • 2011-07-17
  • 2013-04-13
相关资源
最近更新 更多