2

I have a very simple Angular pattern like this:

<div>
    <input [(ngModel)]="testField" name="testField" #testFieldN="ngModel" required pattern="[a-zA-Z]+" />
    <div *ngIf="testFieldN.invalid"
         class="alert alert-danger">
      <div *ngIf="testFieldN.errors?.pattern">
        Title is invalid.
      </div>
      <div *ngIf="testFieldN.errors?.required">
        Title is required.
      </div>
    </div>
  </div>

I expect that testField should have at least one alphabetical character. This means value like "One11" should be accepted. However, if I enter that value, the pattern error kicked off and shows "Title is invalid."

Can someone point out what is wrong? Also, I expect when the filed is empty, the pattern error should be kicked off, but it is not. Why is that?

To make it clear, this is how I test my pattern and it matches "One11": Demo

1 Answer 1

3

Your pattern allows only alphabetical characters, and not numbers, for example. If you want something that accepts numbers, try:

[0-9]*[a-zA-Z]{1,}[0-9]*

It's basically:

  1. 0 or more numbers
  2. at least 1 character of A-z
  3. 0 or more numbers
Sign up to request clarification or add additional context in comments.

4 Comments

I believe we use javascript regular expression syntax for Angular, right? So if I only want alphabetical characters, the pattern should be "^[a-zA-Z]+$". Am I wrong?
Your pattern doesn't allow numbers at all.
Alexey, so what is the pattern that allows at least one alphabetical character?
Alexey, thanks but I don't think it's what I wanted. Can you suggest an expression that accepts a string with at least one alphabetical character? And is it a javascript regular expression?

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.