1

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?

Patrick McDermott
  • 1,220
  • 1
  • 15
  • 30

3 Answers3

3

\w allows words (alphanumeric and underscore combinations) in the RegExp.

Dez
  • 5,702
  • 8
  • 42
  • 51
2

Your original regular expression /^[0-9\s\w\+\-\(\)\']*$/ includes \w which translates to "any word character" which includes, but is not limited to [a-zA-Z].

Remove this from your regex and it should work as expected i.e.

var regex = /^[0-9\s\+\-\(\)\']*$/
phuzi
  • 12,078
  • 3
  • 26
  • 50
1

[^a-zA-Z]+$

Along with other answers the regex with ^ in the [] will exclude any characters from that set. See https://regex101.com/#javascript

Or perhaps you'd want ^[^a-zA-Z]+$

shaunhusain
  • 19,630
  • 4
  • 38
  • 51