i'm working on angular 4 form and set some validations on the input field but the validation is show when the page load's but i want the validation when the form is submitted or the email pattern is not valid.
<form [formGroup]="myForm" (ngSubmit)="onSubmit(myForm.value)"
[class.error]="!myForm.valid && myForm.touched">
  <div class="field" [class.error]="!email.valid && email.touched">
    <label for="email">Email</label>
    <input type="email" id="email" name="email" [formControl]="email">
    <div *ngIf="!email.valid"
     class="ui error message">Email is invalid</div>
   <div *ngIf="email.hasError('required')"
     class="ui error message">Email is required</div>
  </div>
  <div *ngIf="!myForm.valid"
    class="ui error message">Form is invalid</div>
  <button type="submit">login</button>
</form>
Typescript code:
function EmailValidator(control: FormControl): { [s: string]: boolean } {
 if (!control.value.match('^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$')) 
 {
   return {invalidEmail: true};
 }
}
@Component({
 selector: 'app-login-form',
 templateUrl: './login-form.component.html',
 styleUrls: ['./login-form.component.css']
})
export class LoginFormComponent implements OnInit {
myForm: FormGroup;
email: AbstractControl;
constructor(fb:FormBuilder) {
  this.myForm = fb.group({
   'Email': ['', Validators.compose([
    Validators.required, EmailValidator])
  ]
 });
 this.email = this.myForm.controls['Email'];
}
 onSubmit(form: string): void {
  console.log('you submitted value:', form);
 }
}
                you can use
<div 
  *ngIf="myForm.get('email').hasErrors('required') && 
   myForm.get('email').touched">
  Email is required
</div>
And adapt hasError to your validation 
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With