参考:
修仙之路:https://segmentfault.com/a/1190000009053752
Validators.maxLength(200) // html中使用时小写:maxlength
dirty
:input中的值改变过(哪怕又恢复回去了)。初始是false,发生过改变,就是true。
errors
:就是Validators.required
;如果有值,errors是null;如果没值,那么是true。
自定义验证器(antd中的例子):
checkPassword: [null, [Validators.required, this.confirmationValidator]],
confirmationValidator = (control: FormControl): { [s: string]: boolean } => {
if (!control.value) {
return { required: true };
} else if (control.value !== this.validateForm.controls.password.value) {
return { confirm: true, error: true };
}
return {};
};
<nz-form-explain
*ngIf="validateForm.get('checkPassword')?.dirty && validateForm.get('checkPassword')?.errors
<ng-container *ngIf="validateForm.get('checkPassword')?.hasError('required')">
Please confirm your password!
</ng-container>
<ng-container *ngIf="validateForm.get('checkPassword')?.hasError('confirm')">
Two passwords that you enter is inconsistent!
</ng-container>
</nz-form-explain>
this.validateForm.get('productName').hasError('required')
this.validateForm.get('productName').hasError('maxlength'); // 注意:这块不是驼峰式了。
默认Validators具有的函数,查看 /node_modules/@angular/forms/src/validators.d.ts,eg:
min,max,required,email,minLength,maxLength等。
自定义的:
// 中引文,逗号,中划线和下划线
import {AbstractControl, ValidatorFn} from "@angular/forms";
export function KeywordSaftyValidator(): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } | null => {
const value = control.value;
const safty= /^[0-9a-zA-Z\,\,\_\-\u4e00-\u9fa5]*$/.test(value);
if(!safty){
return {keywordSafty:true};
}
return null;
}
}
// get:keywordSafty,如果为true,那么验证不通过;如果false(null值),那么通过。
动态添加错误提示:
this.validateForm.get('productName').setErrors({productNameRepeatForbidden: true})
级联选择 :
<nz-cascader [nzOptions]="categoryTree"
nzPlaceHolder="点击这里选择产品类别"
nzSize="large"
formControlName="categoryId">
</nz-cascader>
<!--[(ngModel)]="values"-->
// 晚一些给categoryId赋值:
this.validateForm.controls['categoryId']
.patchValue([parentId, this.baseInfo.categoryId]);
ngModel是不需要的。
提交:
/**
* 表单提交
*/
submitForm(){
console.log(this.validateForm);
const controls= this.validateForm.controls;
for(const x in controls){
if(controls.hasOwnProperty(x)){
controls[x].markAsDirty(); // 所有都触发dirty
}
}
if(this.validateForm.invalid) return; // 有很多值,判断是否有不合格的校验
console.log('form有错误,会执行么?');
const publishingBaseInfo = {
}
}
修改form的样式
// 会编程全局样式,影响其他页面的样式,所以还是要加中间一层的
::ng-deep .has-error .ant-form-explain{
position:absolute;
bottom:-22px;
left:0;
}
// eg:
::ng-deep .business-license-indentity-edit .has-error .ant-form-explain{
// 样式
}
::ng-deep .business-license-indentity-edit .has-error .ant-form-explain{
position:absolute;
bottom:-22px;
left:0;
}