Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 validation is showing when the page load's

Tags:

html

angular

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);
 }
}
like image 635
ahsan Avatar asked Oct 11 '17 11:10

ahsan


Video Answer


1 Answers

you can use

<div 
  *ngIf="myForm.get('email').hasErrors('required') && 
   myForm.get('email').touched">

  Email is required

</div>

And adapt hasError to your validation

like image 151
t3__rry Avatar answered Sep 20 '22 14:09

t3__rry