3

I have an input field that should only be valid if it contains only digits and no special characters and no spaces. I am using ng-pattern in angular to validate the input.

I have tried using:

/^\d+$/

/^\d*$/

/^[0-9]+$/

These work to prevent special characters and letters, but do nothing about the spaces. Does anyone know a regex that would consider spaces an invalid character? I am trying to avoid preventing the input using keyCode.

I apologize if there's already a thread for this. I found many similar ones but nothing that helped with the spaces.

EDIT: Even if the regex is supposed to prevent spaces normally, it is does not seem to be working with ng-pattern:

<input type="tel" maxlength="10" ng-pattern="/^[0-9]+$/" placeholder="(1234567890)" />

Is still returning the ng-valid-pattern class on the input if I type a space.

3
  • Your regex does not allow spaces. See regex101.com/r/nM1lY8/1
    – PM 77-1
    Oct 25, 2015 at 4:15
  • 2
  • ever figured this out? I'm battling with similar problem, I guess it has to do with angulars ng-pattern not returning false when a space is present in the front of the input. I've got an ng-pattern="/^\\+?[0-9]{6,29}$/" but it still shows as valid even if I start the input with a whitespace.
    – ghoulfolk
    Feb 11, 2020 at 9:43

2 Answers 2

2

This pattern should work: /^\d+$/

-1

Try to use this pattern /^[0-9]{0,}$/ https://regex101.com/r/bT2oO0/1

1
  • it passes for a completely null string
    – Curious96
    Nov 3, 2021 at 18:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.