问题
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