mrk*_*nic 9 validation angular
我有一个非常简单的表单,只有一个输入字段:
this.form = this.fb.group({
emailAddress: ['', [Validators.required, Validators.email]],
});
Run Code Online (Sandbox Code Playgroud)
标记:
<input type="email" class="form-control" formControlName="emailAddress">
Run Code Online (Sandbox Code Playgroud)
该字段有两个验证器,必填和用于电子邮件。
我还有一个提交按钮,配置如下:
<button [disabled]="!form.valid" type="submit">Send</button>
Run Code Online (Sandbox Code Playgroud)
令人困惑的部分是,当我输入错误的电子邮件地址时,例如:
一个@b
提交按钮被启用,从而将表单和输入字段标记为有效。我希望这a@b不是一个有效的电子邮件地址。
我应该使用其他任何角度的电子邮件验证器还是这是一个错误?
Che*_*pan 10
您可以使用模式来实现有效的电子邮件
ngOnInit() {
this.registerForm = this.formBuilder.group({
firstName: ['', Validators.required],
lastName: ['', Validators.required],
email: ['', [Validators.required, Validators.email,Validators.pattern('^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$')]],
password: ['', [Validators.required, Validators.minLength(6)]]
});
}
Run Code Online (Sandbox Code Playgroud)
示例:https : //stackblitz.com/edit/angular-email-validation
您可以使用自定义电子邮件验证
我在Stackblitz上创建了一个演示
组件.html
<form [formGroup]="myForm">
<input type="email" class="form-control" formControlName="emailAddress" placeholder="Enter email">
<button [disabled]="!myForm.valid" type="submit">Send</button>
</form>
Run Code Online (Sandbox Code Playgroud)
组件.ts
myForm: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.myForm = this.fb.group({
emailAddress: [null, [Validators.required, this.emailValidator]]
});
}
emailValidator(control) {
if (control.value) {
const matches = control.value.match(/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/);
return matches ? null : { 'invalidEmail': true };
} else {
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
对于角度,只需添加属性“电子邮件”,如下所示:
<label for="email">Email</label>
<input type="email" id="email" name="email" #email="ngModel"
ngModel class="form-control" email required>
<span class="help-block" *ngIf="!email.valid && email.touched">
Email is invalid
</span>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9948 次 |
| 最近记录: |