import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
registerForm: FormGroup;
submitted = false;
constructor(private formBuilder: FormBuilder) { }
//only number will be add
keyPress(event: any) {
const pattern = /[0-9+- ]/;
let inputChar = String.fromCharCode(event.charCode);
if (event.keyCode != 8 && !pattern.test(inputChar)) {
event.preventDefault();
}
}
ngOnInit() {
this.registerForm = this.formBuilder.group({
phonenumber: ['', [ Validators.required,
Validators.pattern("^[0-9]*$"),
Validators.minLength(10), Validators.maxLength(10)]]
});
}
// convenience getter for easy access to form fields
get f() { return this.registerForm.controls; }
onSubmit() {
this.submitted = true;
// stop here if form is invalid
if (this.registerForm.invalid) {
return;
}
}
}
form [formGroup]="registerForm" (ngSubmit)="onSubmit()"
div class="col-md-4"
div class="form-group"
label for="">YOUR PHONE NUMBER /label
input (keypress)="keyPress($event)" required type="text" formControlName="phonenumber" class="form-control" placeholder="Enter Your phone Number" [ngClass]="{ 'is-invalid': submitted && f.phonenumber.errors }"
div ngIf="submitted && f.phonenumber.errors" class="invalid-feedback"
div ngIf="f.phonenumber.errors.required">Phone number is required /div
div *ngIf="f.phonenumber.errors.pattern || f.phonenumber.errors.maxlength || f.phonenumber.errors.minlength">Phone number must be at least 10 numbers /div
/div
/div
/div
input type="submit" class="mw-ui-btn" value="Submit"
/form
ng-pattern="re"