Trajce12
Trajce12

Reputation: 331

How can i restrict input field to accept just string inside in template approach?

I have input field in form.The user should not be allowed to write numbers inside.Just strings. This is my input in template approach where i am restricting that the length should be minimum 3 characters and is required.

 <input class="form-control"
                 id="productNameId"
                 type="text"
                 placeholder="Name (required)"
                 required
                 minlength="3"
                 [(ngModel)]=product.productName
                 name="productName"
                 #productNameVar="ngModel"
                 [ngClass]="{'is-invalid': (productNameVar.touched || 
                                            productNameVar.dirty ||
                                            product.id !== 0) && 
                                            !productNameVar.valid }" />
          <span class="invalid-feedback">
            <span *ngIf="productNameVar.errors?.required">
              Product name is required.
            </span>
            <span *ngIf="productNameVar.errors?.minlength">
              Product name must be at least three characters.
            </span>
          </span>

Upvotes: 0

Views: 409

Answers (1)

mamichels
mamichels

Reputation: 639

On your input-tag use the pattern attribute to use regex for your validation:

<input ... pattern="[A-Za-z]{3,}" required />

Upvotes: 4

Related Questions