Search code examples
angularangular-reactive-formsangular-validation

Validate a formControl in angular reactive from which contains "@gmail.com"


I have created one userInfo form and i want to validate email field like it should contain @gmail.com, I want only gmail users , I have used reactive forms and i want the emailAddress field to be validated.

Here is my user job form

<div>
  <form  [formGroup]="jobform">
    <div class="form-group">
      <label>Email Address</label>
      <input type="text" formControlName="emailAddress" class="form-control"  />                

    <button [disabled]="!jobform.valid" class="btn btn-primary">Submit</button>

  </form>
</div>

Component.ts :

export class UserInfoComponent implements OnInit {
    userFormGroup: FormGroup  

    constructor(private fb: FormBuilder) { }   

    ngOnInit() {
        this.jobform= this.fb.group({
            emailAddress:['', Validators.required],
        });
    }
}

Solution

  • You can add a regex check in the form control which checks your requirement. An apt regex for your requirement could be /^.+@gmail.com$/

    You can add the validator as:

    this.jobform= this.fb.group({
         emailAddress: ['', [Validators.required, Validators.email, Validators.pattern('^.+@gmail.com$')]]
    });