javascript - 角度的电子邮件验证
问题描述
我正在尝试向电子邮件添加验证。
结构:使用响应式表单,获取电子邮件并使用过滤器 javascript 检查是否已存在。
组件.ts:
isUniqueEmail(): ValidatorFn {
return (control: AbstractControl): any | null => {
if(control.value.email != null){
this.httpService
.getDataFromServer("api/employees?company_branch=" +this.user.branch_id)
.subscribe((resp) => {
var data = resp.data.employee;
const found = data.filter(v => v.email == control.value.email);
if(found.length !== 0){
console.log("found one");
return {exist: true}
}
});
}
}
}
如果电子邮件已经存在 console.log 打印找到并且一切正常。
表单控制声明:
this.employeeForm = new FormGroup({
email: new FormControl(null,
[
Validators.required,
Validators.pattern("^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$"),
ValidatorsSettings.notOnlyWhitespace,
]),
),{validators: this.isUniqueEmail()}}
在 html 中:
<div class="row">
<div class="from-group">
<label for="Email"> Email </label>
<mat-divider></mat-divider>
<input
type="text"
id="Email"
class="form-control"
formControlName="email"
/>
<div *ngIf="employeeForm.get('email').invalid && (employeeForm.get('email').touched || employeeForm.get('email').dirty)" class="help-block">
<div *ngIf="employeeForm.get('email').errors.required || employeeForm.get('email').errors.notOnlyWhitespace" class="help-block">
Email is required
</div>
<div *ngIf="employeeForm.get('email').errors.pattern" class="help-block">
Email must be a valid email address format
</div>
<mat-error *ngIf="employeeForm.errors?.exist" class="help-block"
>Email Already Exist</mat-error>
</div>
</div>
</div>
错误未显示!我做错了什么?
解决方案
由于验证器使用服务来请求响应,因此它应该是asyncValidator。代码最终可能是:
isUniqueEmail(): AsyncValidatorFn {
return (control: AbstractControl): Observable<ValidationErrors>=> {
if(control.value.email != null){
return this.httpService
.getDataFromServer("api/employees?company_branch="+this.user.branch_id).pipe(
.map((resp) => {
var data = resp.data.employee;
const found = data.filter(v => v.email == control.value.email);
if(found.length !== 0){
console.log("found one");
return {exist: true}
}
});
}
else return null;
}
}
推荐阅读
- java - 调用 init 方法失败;嵌套异常是 java.lang.IllegalArgumentException:需要命名空间属性
- excel - 使用公式提取具有相同行名的所有信息(不同)形成一个excel工作表
- html - 在 Edge 中禁用视频自动播放并在 IE 中禁用下载
- ios - 在 Swift 中取消可选计时器的语法
- c# - ASP.NET Core Identity UserManager 使用 FindByEmailAsync 查找不存在的用户
- regex - 当任何字符串至少包含三个字符并且 + 号被最少三个字符包围时匹配的正则表达式
- python - Tkinter 将图像放入框架,背景
- ats - 在堆栈上分配数据类型
- c - 检查数组中的数字是否具有公因数的省时方法?
- html - 折叠后我的导航栏不会将项目显示为列表