I have a custom directive
in my Angular app for form validation. I have a phone input
which should only accept numeric values, for which I have created a `regExp':
var regExp = /^[0-9\s\w\+\-\(\)\']*$/;
Which I have then used within a condition within a function like so:
.directive('validatePhone', function(){
var regExp = /^[0-9\s\w\+\-\(\)\']*$/;
return {
require: 'ngModel',
link: function(scope, elem, attr, ctrl) {
function myValidation(value) {
if (regExp.test(value)) {
ctrl.$setValidity('validPhone', true);
} else {
ctrl.$setValidity('validPhone', false);
}
return value;
}
ctrl.$parsers.push(myValidation);
}
}
})
If I enter any special character such as $%!
it pops up with an error in the front-end, so works. For some reason it is still accepting alpha values. I then extended the the condition to evaluate to true only if the input
value does not contain alpha values, like so:
.directive('validatePhone', function(){
var regExp = /^[0-9\s\w\+\-\(\)\']*$/;
var regExc = /^[a-zA-Z]+$/; //new reg exp
return {
require: 'ngModel',
link: function(scope, elem, attr, ctrl) {
function myValidation(value) {
if ((regExp.test(value)) && (!regExc.test(value))) {
ctrl.$setValidity('validPhone', true);
} else {
ctrl.$setValidity('validPhone', false);
}
return value;
}
ctrl.$parsers.push(myValidation);
}
}
})
If I enter an alpha value at the beginning it flags the validation as false. But if I enter numeric then alpha values, it returns true 0178ar
, which isn't what I want.
Question
Why is my validation allowing alpha characters to be entered when I specified for it not to?