English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Implementation Code of Custom Directive for Form Password Verification in angularjs

HTML code

<form name="form">
    <input type="password" name="password" ng-model="password" required placeholder="Please enter the password">
    <input type="password" name="passwordConfirm" ng-model="passwordConfirm" equal-to="password" placeholder="Please enter the password again">
    <span ng-show="form.passwordConfirm.$error.equalTo">Passwords do not match</span>
  </form>

js

angular.module("Valid",[])
.directive("equalTo", function () {
  return {
    require: "ngModel",
    link: function (scope, ele, attrs, ctrl) {
      console.log(scope);//Print the current scope
      console.log(attrs);//Print the current tag attribute list
      console.log(ctrl);//Print current ctrl
      var target = attrs["equalTo"];//Get the key value of the custom directive attribute
      if (target) {//Check if the key exists
        scope.$watch(target, function () {//Exist to start listening to its value
          ctrl.$validate()//Manually call validation each time there is a change
        ) 
        // Get the parent controller FormController of the current model controller
        var targetCtrl = ctrl.$$parentForm[target];//Get the specified model controller
        console.log(targetCtrl)
        ctrl.$validators.equalTo = function (modelValue, viewVale) {//Custom validator content
          var targetValue = targetCtrl.$viewValue;//Get the input value of password
          return targetValue == viewVale;//Is equal to the value of passwordConfirm
        }
        ctrl.$formatters.push(function (value) {
          console.log("The value being formatted:", value)
          return value;
        )
        ctrl.$parsers.push(function (value) {
          console.log("The value being converted:", value)
          return value;
        )
      }
    }
  }
)

Demo Address:https://tianyouh.github.io/angularPasswordConfirm/

You May Also Like