This is an interesting problem, complex Angular validation. The following fiddle implements what you want:
I created a new directive, rpattern
, that is a mix of Angular's ng-required
and the ng-pattern
code from input[type=text]
. What it does is watch the required
attribute of the field and take that into account when validating with regexp, i.e. if not required mark field as valid-pattern
.
A dirty (but smaller) solution, if you do not want a new directive, would be something like:
$scope.phoneNumberPattern = (function() {
var regexp = /^\(?(\d{3})\)?[ .-]?(\d{3})[ .-]?(\d{4})$/;
return {
test: function(value) {
if( $scope.requireTel === false ) {
return true;
}
return regexp.test(value);
}
};
})();
And in HTML no changes would be required:
<input type="text" ng-model="..." ng-required="requireTel"
ng-pattern="phoneNumberPattern" />
This actually tricks angular into calling our test()
method, instead of RegExp.test()
, that takes the required
into account.