Form Validation - Email Validation not working as expected in AngularJs

后端 未结 6 735
北荒
北荒 2020-12-25 12:35

I am using Angular for form validation.

Here is what I use - plunker-edit I have taken this code from Angularjs documentation - Binding to form and control state Hav

6条回答
  •  臣服心动
    2020-12-25 13:12

    I have written a directive that uses the same email validation regular expression that ASP.Net uses. While this may not cover 100% of scenarios, it will cover the vast majority and works perfectly for what we need to cover.

    function email() {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, elem, attrs, ctrl) {
            if (!ctrl) {
                return false;
            }
    
            function isValidEmail(value) {
                if (!value) {
                    return false;
                }
                // Email Regex used by ASP.Net MVC
                var regex = /^[\w-]+(\.[\w-]+)*@([a-z0-9-]+(\.[a-z0-9-]+)*?\.[a-z]{2,6}|(\d{1,3}\.){3}\d{1,3})(:\d{4})?$/i;
                return regex.exec(value) != null;
            }
    
            scope.$watch(ctrl, function () {
                ctrl.$validate();
            });
    
            ctrl.$validators.email = function (modelValue, viewValue) {
                return isValidEmail(viewValue);
            };
        }
    };
    }    
    

    Use it like this:

    
    

提交回复
热议问题