Search This Blog

Wednesday, September 30, 2015

AngularJS - Email and Compare Email Validation

<!DOCTYPE html>
<html ng-app="app">
<head lang="en">
    <meta charset="utf-8">
    <title>Custom Plunker</title>
    <link rel="stylesheet" href="style.css">
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
    <script>
        var app = angular.module('app', [], function () { });

        app.directive('match', function ($parse) {
            return {
                require: 'ngModel',
                link: function (scope, elem, attrs, ctrl) {
                    scope.$watch(function () {
                        return $parse(attrs.match)(scope) === ctrl.$modelValue;
                    }, function (currentValue) {
                        ctrl.$setValidity('mismatch', currentValue);
                    });
                }
            };
        });

        app.controller('FormController', function ($scope) {
            $scope.fields = {
                email: '',
                emailConfirm: ''
            };

            $scope.submit = function () {
                alert("Submit!");
            };
        });
    </script>
</head>
<body ng-controller="FormController">
    <form name='appForm'>
                <input id="email" name="email" ng-model="fields.email"
                       class="input-xlarge" type="text" />
                <input name="emailConfirm" ng-model="fields.emailConfirm"
                       class="input-xlarge"
                       type="text" match="fields.email" />
                <div ng-show="appForm.emailConfirm.$error.mismatch">
                    <span class="msg-error">Email and Confirm Email must match.</span>
                </div>
    </form>
</body>

</html>

No comments:

Post a Comment