简体   繁体   中英

Create AngularJS Directive to Validate on Blur

Hoping to re-create some of the functionality that's available to us in Angular 1.3.X -- the app I am creating has to work well (or at least well-enough) in IE 8. For that reason, I am (sadly) constrained to not using 1.3.X. I've been running into some trouble trying to emulate the $ng-touched attr that is available in 1.3.X.

One part of our app needs to alert users that their form element is invalid if they've tab -bed through it. As it stands, it doesn't set the $invalid attr on any form elements unless I've entered in text and deleted it. I tried using $pristine and $dirty to achieve $invalid after tabbing through, but they both seem to act based on the input's value, not whether it's been touched (maybe this was one of the big advantages of 1.3.X)

Goal : when a user tabs through a form, validations can be fired and set each empty form element as $invalid if it's blank. Basically to emulate the behavior of the $ng-touched attr in 1.2.X. Here's what I have so far:

angular.module('goodStewardApp')
.directive('chf-validate', function () {
return {
  require: 'ngModel',
  link: function(scope, elm, attrs, ctrl) {
    $(elm).blur(
      function(elm) {
        ctrl.$setValidity(elm, false);
      }
    );
  }
};
});

Any help would be greatly appreciated. Thanks!

Turns out the best way to accomplish emulating the behavior of ng-touched in angular 1.2.x is to use ngBlur to set a validation attribute to be true. So:

<form name="aForm">

   <input name="foo" ng-model="foo.bar" ng-blur="validateThisElement=true" ng-required="true">

   <div ng-show="aForm.foo.$error.required && validateThisElement"> 
      Oh no! An alert!
   </div>

</form>

This allows you to run a validation after a user tab s through your form, a common way that people used to using computers will use to interact with your angular form/app. Hope this helps anyone still stuck w/ 1.2.X for IE8 reasons!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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