Home > Enterprise >  angular pattern validation is not working. While working on online regex
angular pattern validation is not working. While working on online regex

Time:05-04

I am using pattern validation in angular button it is not working. In pattern validation on alphabet and numeric is allowed but it accept special character.

<mat-form-field  appearance="fill">
                                        <input matInput placeholder={{fields.placeholder_text}}
                                        [(ngModel)]="fields.value" 
                                        fields.id="ngModel" pattern="/[a-zA-Z0-9]/">
                                        <div *ngIf="!fields.value  &&  fields.required == true" >
                                            fields is required.
                                            
                                          </div>
                                          <div *ngIf="fields.value" >
                                            
                                            <div *ngIf="fields.hasError('pattern')"> 
                                                fields is not valid.
                                             </div> 
                                          </div>
                                         
                                    </mat-form-field>

CodePudding user response:

Try with fields.errors?.pattern in your *ngIf.

CodePudding user response:

Just wrap inputs with form tag and have template variable to the form tag as in the following code, each input must have the name tag based on this we can show the error

Here in the example patter will allow only numbers and alphabets

Main thing is #frm and input with name attribute

HTML

<form #frm="ngForm">
  <input name="name" [(ngModel)]="formData.name" pattern="^[A-z0-9]*$" />
  <div *ngIf="frm.form.controls.name?.errors?.pattern">
    Invalid Pattern allowed only alphabets and numbers
  </div>
</form>

Component

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {

  formData = {
    name: '',
  };

}
  • Related