Angular conditional email validation

二次信任 提交于 2019-12-25 02:35:31

问题


How can I conditionally use angular's email validation based on the presence of another scope variable? I looked through the documentation but the only way I can find to trigger email validation is to use input type="email", which in this case I cannot use due to the dependence of another directive on type="text".

Ideally I'd either like to assign ng-match="email" based on the value of another scope variable, or just validate the email programatically on submission. In theory I could just a separate email validation regex but if possible I'd like to use Angular's validation since I use that everywhere else.

Thanks

-- Edit: To clarify, I specifically would like to use angular's native email validation in whatever solution I end up using.


回答1:


You should use ng-required and ng-pattern on the email input field.

<input type="text" ng-model="email" ng-required="emailRequired" ng-pattern="emailPattern" />

And then define emailPattern as function on the $scope of your controller.

$scope.emailPattern = (function() {
var regexp = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return {
    test: function(value) {
        if( $scope.emailRequired === false ) return true;
        else return regexp.test(value);
    }
};

})();

The following fiddle implements what you want:

http://jsfiddle.net/9SSE4/




回答2:


Could you change the type of the input? If the input should be validated as an email then set its type to an email, else set it to text.

<input type="{{vm.type}}" ng-model="vm.text" />
<select ng-model="vm.type">
  <option>text</option>
  <option>email</option>

Example Plunker



来源:https://stackoverflow.com/questions/21370006/angular-conditional-email-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!