页面加载时会显示Angular 4验证

时间:2017-10-11 11:13:13

标签: html5 angular

我正在处理角度4表单并在输入字段上设置一些验证但是在页面加载时会显示验证但是我希望在提交表单或电子邮件模式不是时进行验证有效的。

<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>

打字稿代码:

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);
 }
}

1 个答案:

答案 0 :(得分:1)

你可以使用

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

  Email is required

</div>

并使hasError适应您的验证