user3636476 February 2016

AngularJS, issue on form validation

I have a form where the user needs to enter 2 times his email. I found on the internet (but not able to find the link anymore) some angular code doing what I wanted. The only issue is when the 2 emails are the same, one input still got the class

.ng-invalid.ng-dirty

So I can't submit the form.

My code is the following:

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)
            })
                

Answers


Stepan Kasyanenko February 2016

Im update your jsfiddle. You don't return value from ctrl.$parsers.unshift.

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

Updated jsfiddle

Post Status

Asked in February 2016
Viewed 3,657 times
Voted 7
Answered 1 times

Search




Leave an answer