名称验重

40次阅读

共计 1433 个字符,预计需要花费 4 分钟才能阅读完成。

本周写的项目需要对名称进行验重,采用的是 angular 的异步验证器的方式.
后台接口
首先要查询数据库表中是否存在相同名称,需要一个验证重复的后台接口:
/**
* @description 是否存在姓名
* @param name 姓名
* @return java.lang.Boolean
* @author htx
* @date 下午 7:19 19-3-28
**/
@GetMapping(“existByName/{name}”)
public Boolean existByName(@PathVariable String name) {
return majorService.existsByName(name);
}
只需要查询数据库中是否存在该名称,返回 true 或 false 即可.
前台验证
因为在编辑和添加时都需要验证,于是就把获取验证方法写在了服务里,从服务里获取验证方法:
/**
* @description 获取名称是否重复的验证器
* @param name 当 name 存在时 默认跳过 name(用于编辑可能保留原名称)
* @return AsyncValidatorFn 异步验证器
* @author htx
* @date 下午 7:53 19-3-28
**/
getValidatorNameExistFn(): AsyncValidatorFn {
return (control: AbstractControl): Observable<ValidationErrors | null> => {
return this.existByName(control.value).pipe(
map(exist => (exist ? {exist: true} : null)),
catchError(() => null)
);
};
}

/**
* @description 是否存在相同编号名称
* @param name 名称
* @author htx
* @date 下午 7:45 19-3-28
**/
existByName(name: string): Observable<boolean> {
return this.http.get<boolean>(this.baseUrl + ‘/existByName/’ + name);
}
执行 getValidatorNameExistFn() 方法就会获取验证名字是否重复的异步验证方法, 因为 AsyncValidatorFn 接口要求返回的是 Observable<ValidationErrors | null>, 但我们后台接口返回的是 true 或 false, 因此需要用 map 操作符进行转换. 在建立控件的时候将验证方法加入异步验证即可:
this.validateForm = this.fb.group({
name: [null, [Validators.required], [this.majorService.getValidatorNameExistFn()]],
number: [null, [Validators.required], [this.majorService.getValidatorNumberExistFn()]],
college: [null],
teacherList: [null]
});
v 层中增加提示信息:
<nz-form-explain *ngIf=”validateForm.get(‘name’).dirty && validateForm.get(‘name’).errors?.exist”> 专业名称已存在!
</nz-form-explain>
效果:

正文完
 0