carmouche
carmouche

Reputation: 159

Regex for numbers only (no spaces or special chars) using ng-pattern

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.

Upvotes: 3

Views: 18357

Answers (2)

Eli Front
Eli Front

Reputation: 775

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

Upvotes: 3

Vlad Kosko
Vlad Kosko

Reputation: 84

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

Upvotes: -1

Related Questions