angular4中响应式表单的验证如何做到统一错误处理?

各位大家,请问下angular4中响应式表单的验证如何做到统一错误处理?

我看了angular4的很多例子(包含官网),验证错误都是单独写的

如:


 <div nz-form-control nz-col [nzSpan]="8" nzHasFeedback [nzValidateStatus]="getFormControl('name')">

            <nz-input formControlName="name" [nzId]="'name'"></nz-input>

            <div nz-form-explain *ngIf="validateFormControl('name','required')">名称必填</div>

            <div nz-form-explain *ngIf="validateFormControl('name','rangeLength')">名称最多100个字符 </div>

            <div nz-form-explain *ngIf="validateFormControl('name','servererror')" class="servererror">{{getErrorValueForFormControl('name','servererror')}}</div>

        </div>

这样界面感觉好多重复代码,能不能做统一处理,如检查的名称没有填写,自动生成


<div nz-form-explain *ngIf="validateFormControl('name','required')">名称必填</div>

这段代码


谢谢!


开心每一天1111
浏览 1278回答 1
1回答

呼如林

可以的。简略代码如下:html:&nbsp; <input type="text"&nbsp; formControlName="account">&nbsp; <div *ngIf="formErrors.account" class="alert alert-danger">{{ formErrors.account }}</div>&nbsp;&nbsp;&nbsp; <input type="password"&nbsp; formControlName="password">&nbsp; <div *ngIf="formErrors.password" class="alert alert-danger">{{ formErrors.password }}</div>&nbsp;&nbsp;ts:editForm: FormGroup;formErrors = {&nbsp; &nbsp; 'account': '',&nbsp; &nbsp; 'password': ''};validationMessages = {&nbsp; &nbsp; 'account': {&nbsp; &nbsp; &nbsp; &nbsp; 'required': '请输入用户名',&nbsp; &nbsp; &nbsp; &nbsp; 'maxlength': '用户名不能超过20位'&nbsp; &nbsp; },&nbsp; &nbsp; 'password': {&nbsp; &nbsp; &nbsp; &nbsp; 'required': '请输入密码',&nbsp; &nbsp; &nbsp; &nbsp; 'minlength': '密码至少6位',&nbsp; &nbsp; &nbsp; &nbsp; 'maxlength': '密码必须小于16位',&nbsp; &nbsp; &nbsp; &nbsp; 'pattern': '密码需要包含大小写和数字'&nbsp; &nbsp; }};&nbsp;ngOnInit() {&nbsp;&nbsp;this.editForm = new FormGroup({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; account: new FormControl('', [Validators.required, Validators.maxLength(20)]),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; password: new FormControl('', [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Validators.minLength(6),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Validators.maxLength(16),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Validators.required,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Validators.pattern('^(?=.*[A-Z])(?=.*[0-9])(?=.*[a-z])[0-9a-zA-Z]{6,16}$')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ])&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; this.editForm.valueChanges.subscribe(() => this.onValueChanged());&nbsp; &nbsp;// 监听每次输入内容,获得错误信息&nbsp; }&nbsp;&nbsp;&nbsp; onValueChanged() {&nbsp; &nbsp; for (const item in this.formErrors) {&nbsp; &nbsp; &nbsp; &nbsp; this.formErrors[item] = '';&nbsp; &nbsp; &nbsp; &nbsp; for (const key in this.editForm.get(item).errors) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.formErrors[item] += this.validationMessages[item][key] + ' ';&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}&nbsp;&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript