我使用模板驱动的方法在Angular 2中构建表单,并且我已经成功创建了可以在模板中使用的自定义验证器。
但是,我找不到一种方法来显示绑定到特定错误的特定错误消息。我想区分为什么表单无效。我该怎么做?
import { Component } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Site } from './../site';
import { BackendService } from './../backend.service';
import { email } from './../validators';
import { CustomValidators } from './../validators';
@Component({
templateUrl: 'app/templates/form.component.html',
styleUrls: ['app/css/form.css'],
directives: [CustomValidators.Email, CustomValidators.Url, CustomValidators.Goof],
providers: [BackendService]
})
export class FormComponent {
active = true;
submitted = false;
model = new Site();
onSubmit() {
this.submitted = true;
console.log(this.model);
}
resetForm() {
this.model = new Site();
this.submitted = false;
this.active = false;
setTimeout(() => this.active = true, 0);
}
get diagnostics() {
return JSON.stringify(this.model)
}
}
import { Directive, forwardRef } from '@angular/core';
import { NG_VALIDATORS, FormControl } from '@angular/forms';
import { BackendService } from './backend.service';
function validateEmailFactory(backend:BackendService) {
return (c:FormControl) => {
let EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
return EMAIL_REGEXP.test(c.value) ? null : {
validateEmail: {
valid: false
}
};
};
}
export module CustomValidators {
@Directive({
selector: '[email][ngModel],[email][formControl]',
providers: [
{provide: NG_VALIDATORS, useExisting: forwardRef(() => CustomValidators.Email), multi: true}
]
})
export class Email {
validator:Function;
constructor(backend:BackendService) {
this.validator = validateEmailFactory(backend);
}
validate(c:FormControl) {
return this.validator(c);
}
}
@Directive({
selector: '[url][ngModel],[url][formControl]',
providers: [
{provide: NG_VALIDATORS, useExisting: forwardRef(() => CustomValidators.Url), multi: true}
]
})
export class Url {
validator:Function;
constructor(backend:BackendService) {
this.validator = validateEmailFactory(backend);
}
validate(c:FormControl) {
var pattern = /(https?:\/\/)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/;
return pattern.test(c.value) ? null : {
validateEmail: {
valid: false
}
};
}
}
@Directive({
selector: '[goof][ngModel],[goof][formControl]',
providers: [
{provide: NG_VALIDATORS, useExisting: forwardRef(() => CustomValidators.Goof), multi: true}
]
})
export class Goof {
validate(c:FormControl) {
return {
validateGoof: {
valid: false
}
};
}
}
}
答案 0 :(得分:14)
您可以检查AbstractControl#hasError(...)
方法以查看控件是否有特定错误。 FormGroup
和FormControl
都是AbstractControl
。对于FormControl
,您只需将错误名称作为参数传递。例如
function regexValidator(control: FormControl): {[key:string]: boolean} {
if (!control.value.match(/^pee/)) {
return { 'badName': true };
}
}
<div *ngIf="!nameCtrl.valid && nameCtrl.hasError('badName')"
class="error">Name must start with <tt>pee</tt>.
</div>
验证器方法应该返回一个字符串/布尔映射,其中键是错误的名称。这是您在hasError
方法中检查的名称。
对于FormGroup
,您可以将FormControl
的路径作为额外参数传递。
<div *ngIf="!form.valid && form.hasError('required', ['name'])"
class="error">Form name is required.</div>
name
只是输入FormControl
的标识符。
以下是FormControl
和FormGroup
检查的示例。
import { Component } from '@angular/core';
import {
FormGroup,
FormBuilder,
FormControl,
Validators,
AbstractControl,
REACTIVE_FORM_DIRECTIVES
} from '@angular/forms';
function regexValidator(control: FormControl): {[key:string]: boolean} {
if (!control.value.match(/^pee/)) {
return { 'badName': true };
}
}
@Component({
selector: 'validation-errors-demo',
template: `
<div>
<h2>Differentiate Validation Errors</h2>
<h4>Type in "peeskillet"</h4>
<form [formGroup]="form">
<label for="name">Name: </label>
<input type="text" [formControl]="nameCtrl"/>
<div *ngIf="!nameCtrl.valid && nameCtrl.hasError('required')"
class="error">Name is required.</div>
<div *ngIf="!nameCtrl.valid && nameCtrl.hasError('badName')"
class="error">Name must start with <tt>pee</tt>.</div>
<div *ngIf="!form.valid && form.hasError('required', ['name'])"
class="error">Form name is required.</div>
</form>
</div>
`,
styles: [`
.error {
border-radius: 3px;
border: 1px solid #AB4F5B;
color: #AB4F5B;
background-color: #F7CBD1;
margin: 5px;
padding: 10px;
}
`],
directives: [REACTIVE_FORM_DIRECTIVES],
providers: [FormBuilder]
})
export class ValidationErrorsDemoComponent {
form: FormGroup;
nameCtrl: AbstractControl;
constructor(formBuilder: FormBuilder) {
let name = new FormControl('', Validators.compose([
Validators.required, regexValidator
]));
this.form = formBuilder.group({
name: name
});
this.nameCtrl = this.form.controls['name'];
}
}
好的,所以我让它运转了,但它有点冗长。我无法弄清楚如何正确访问输入的单个FormControl
。所以我所做的只是创建对FormGroup
<form #f="ngForm" novalidate>
然后检查有效性,我只使用传递了表单控件名称路径的hasError
重载。对于使用<input>
和name
的{{1}},ngModel
值会添加到主name
,其名称为FormGroup
。所以你可以像
FormControl
假设`f.form.hasError('require', ['nameCtrl'])`
。请注意name=nameCtrl
。 f.form
是f
个实例,其NgForm
成员变量为FormGroup
。
以下是重构的例子
form
答案 1 :(得分:2)
我在AngularJs中编写了一组类似于ng-messages
的指令来解决Angular中的这个问题。 https://github.com/DmitryEfimenko/ngx-messages
<div [val-messages]="myForm.get('email')">
<span val-message="required">Please provide email address</span>
<span val-message="server" useErrorValue="true"></span>
</div>
答案 2 :(得分:-1)
对于模板驱动验证,请使用如下属性指令:
import { Model } from '../../models';
import { Directive, Attribute, forwardRef, Input } from '@angular/core';
import { NG_VALIDATORS, Validator, AbstractControl } from '@angular/forms';
@Directive({
selector: '[unique-in-list][formControlName],[unique-in-list][formControl],[unique-in-list][ngModel]',
providers: [
{ provide: NG_VALIDATORS, useExisting: forwardRef(() => UniqueInListDirectiveValidator), multi: true }
]
})
export class UniqueInListDirectiveValidator implements Validator {
@Input('list') private list: Model[];
@Input('property') private _property: string;
@Input('thisid') private _myId: string;
validate(control: AbstractControl): { [key: string]: any } {
let currValue = control.value;
if (currValue && currValue.length > 0 && this.list && Array.isArray(this.list) && this.list.length > 0) {
let model = this.list.find(
(testModel: Model) => {
return testModel.modelId !== this._myId && testModel[this._property] === currValue;
}
);
if (model) {
return { isUnique: true }
}
}
return null;
}
}
..并在模板中附带标记:
<input
type="text"
#nameVar="ngModel"
name="name"
class="form-control name-field"
unique-in-list
[list]="models"
[thisid]="model.modelId"
property="name"
[(ngModel)]="model.name"
required
/>
<div *ngIf="nameVar.errors?.required && (submitted || !nameVar.pristine)" class="alert-classes-here">
<div>Name is required</div>
</div>
<div *ngIf="nameVar.errors?.isUnique && (submitted || !nameVar.pristine)" class="alert-classes-here">
<div>Name is already taken</div>
</div>
HTH