2

As I mentioned in my title I am trying to validate the user entered mobile number is a indian number or not .

For that I have referred a pattern from this regular expression for Indian mobile numbers

But in my case it always returns false.

I want to validate the following .

  • number should starts with 6,7,8,9
  • must have 10 digits

app.component.html

<form class="example-form" [formGroup]="userAddressValidations">
    <mat-form-field appearance="outline" class="col-sm-6">
        <mat-label>10-digit Mobile Number</mat-label>
        <input matInput formControlName="mobileNumber" maxlength="10" (keypress)=_keyPress($event)>
        <mat-error *ngIf="userAddressValidations.get('mobileNumber').hasError('required')">
            Please fill out this field.
        </mat-error>
        <mat-error *ngIf="userAddressValidations.get('mobileNumber').hasError('pattern')">
            It is not a valid mobile number.
        </mat-error>
    </mat-form-field>

</form>

app.component.ts

export class InputErrorStateMatcherExample {
  userAddressValidations: FormGroup;
  constructor(private formBuilder: FormBuilder) { }
  ngOnInit() {
    this.userAddressValidations = this.formBuilder.group({
      mobileNumber: ['', [Validators.required, Validators.pattern('^[6-9]\d{9}$')]]
    });

  }
  _keyPress(event: any) {
    const pattern = /[0-9]/;
    let inputChar = String.fromCharCode(event.charCode);
    if (!pattern.test(inputChar)) {
        event.preventDefault();

    }
}
}

Stackblitz :https://stackblitz.com/edit/angular-mat-form-validation-eg-4jag5u?file=app%2Finput-error-state-matcher-example.ts

can anyone help me to fix it.

Zhu
  • 3,679
  • 14
  • 45
  • 76

2 Answers2

8

You may use

Validators.pattern('[6-9]\\d{9}')

The ^ and $ are added automatically when the pattern is set with the help of a string literal. Alternatively, you may use a regex literal notation (then, ^ and $ are required):

Validators.pattern(/^[6-9]\d{9}$/)

Note that ^ and $ play no role in this concrete snippet since you limit the number of input chars with maxlength="10" attribute.

See the resulting regex demo and the updated Stackblitz demo.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
1

This is most easiest way to validate the Mobile Number in Angular.

<input class="input" id="phoneNumber" type="tel" placeholder="Your Mobile number [(ngModel)]="phone_number" pattern="^[7-9][0-9]{9}$" ngModel phone #phone="ngModel" maxlength="10" minlength="10">

  <div class="" *ngIf="phone.touched && !phone.valid">
      <div class="tag" *ngIf="phone.errors.required">Mobile No. is required. 
      </div>
      <div  class="tag" *ngIf=" phone.errors.pattern">Inaild Mobile Number</div>
  </div>
Sanchit
  • 51
  • 1
  • 4