0

Never really used AngularJS and am having issues figuring out how to create a regex for an input to check/allow only first 2 characters to be letters & the rest numbers.

Hope this makes sense.

Using pugJS

.e-field
    label.e-field__label(for='invoiceNr') Invoice Number
    input#invoiceNumberInput.e-input(
      ng-model='$ctrl.invoiceNumber'
      name="invoiceNumber"
      ng-required="true"

invoiceNr example: HN123123123

The ng-pattern was the answer. This is what I used:

ng-pattern="/^[a-zA-Z]{2}[0-9]{6,}$/"

2 Answers 2

1

Regex for first 2 character is number and rest is digits in angularJS input is as below. Use ng-pattern and the specified RegEX

ng-pattern="/^[a-zA-Z]{2}[0-9]*$/"
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I don't know why I didn't come by this 'ng-pattern' in my searches... it worked well :)
0

Not sure about the integration into Angular. However as a RegEx I think you could use this:

^[a-zA-Z]{2}[0-9]+$

(See test here)

...Just a quick comment regarding the use of ..[0-9]+$ as opposed to ...[0-9]*$

I think you should use + and not *. Otherwise a string like "HN" will also validate but I understood you only want to validate if it has numbers after the letters (like "HN1" or "HN123"..). For this case you should use "+".

3 Comments

Thanks! It was the integration part I was having the issue with :) "ng-pattern="/^[a-zA-Z]{2}[0-9]*$/"" from above worked, in case you're interested in the implementation
Hi @iNano! Thanks! I just added to my answer regarding the use of + versus * - I also updated the linked example. I think in your case you want to use +$ at the end of the RegEx and not *$ . That way it requires to have at least one number following the letters. Cheers! :)
Awesome. Thanks! Good information to have regarding the */ +

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.