How to disable angulars type=email validation?

前端 未结 5 1690
迷失自我
迷失自我 2020-12-16 14:01

How would you go about disabling, or at the very least changing, how Angular validates type=email inputs?

Currently, if you use type=email, Angular essentially doubl

5条回答
  •  庸人自扰
    2020-12-16 14:50

    Echoing nfiniteloop, you don't need to mess with the $parsers or $formatters to override the default validators. As referenced in the Angular 1.3 docs, the $validators object is accessible on the ngModelController. With custom directives you can write as many different email validation functions as you need and call them wherever you want.

    Here's one with a very nice standard email format regex from tuts: 8 Regular Expressions You Should Now (probably identical to Angular's default, idk).

    var app = angular.module('myApp', []);
    
    app.directive('customEmailValidate', function() {
      return {
        require: 'ngModel',
        link: function(scope, elm, attrs, ctrl) {
    
          var EMAIL_REGEXP = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
    
          ctrl.$validators.email = function(modelValue, viewValue) {
            if (ctrl.$isEmpty(modelValue)) {
              // consider empty models to be valid
              return true;
            }
    
            if (EMAIL_REGEXP.test(viewValue)) {
              // it is valid
              return true;
            }
    
            // it is invalid
            return false;
          };
        } 
      };
    });
    

    Here's one that removes validation entirely:

    var app = angular.module('myApp', []);
    
    app.directive('noValidation', function() {
      return {
        require: 'ngModel',
        link: function(scope, elm, attrs, ctrl) {
          ctrl.$validators.email = function(modelValue, viewValue) {
            // everything is valid
            return true;
          };
        } 
      };
    });
    

    To use in your markup:

    
    
    
    
    
    

提交回复
热议问题