从组件内部检查 Angular2 表单是否有效
Checking whether an Angular2 form is valid or not from within the component
我正在尝试检查表单是否有效,以防止在无效时进一步执行。
这是我的表格:
<form (ngSubmit)="updateFirstName(firstNameForm)" #firstNameForm="ngForm" novalidate>
<div class="form-group" ng-class="getCssClasses(formCtrl, formCtrl.firstName)">
<div class="input-group">
<input type="text"
ngControl="firstName"
#firstName="ngForm"
required
minlength="2"
maxlength="35"
pattern_="FIRST_NAME_PATTERN"
[ngModel]="currentUserAccount?.firstName"
(ngModelChange)="currentUserAccount ? currentUserAccount.firstName = $event : null"
placeholder="{{'FIRST_NAME_FORM.NEW_FIRST_NAME'| translate }}"
class="form-control"/>
</div>
<div [hidden]="firstName.valid">
<div *ngIf="firstName?.errors?.minlength" class="control-label">{{'FIRST_NAME_FORM.MIN_LENGTH'| translate}}</div>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary pull-right" [disabled]="buttonDisabled">{{'FIRST_NAME_FORM.SUBMIT'| translate}}</button>
<a [routerLink]="['/dashboard/useraccount']" class="btn btn-link pull-right text-right">{{'FORM_CANCEL' | translate}}</a>
</div>
</form>
但是,当我提交无效表单时,我注意到在控制台中 NgForm
的有效属性是 true
...
updateFirstName(firstNameForm) {
console.log(firstNameForm);//the valid attribute of firstNameForm is true...
}
谁能告诉我为什么会这样?
这是预期的行为
我在 2.0.0-alpha.46 (2015-11-11) 的更改日志中找到
Previously, the controlsErrors getter of ControlGroup and ControlArray returned the errors of their direct children. This was confusing because the result did not include the errors of nested children (ControlGroup -> ControlGroup -> Control). Making controlsErrors to include such errors would require inventing some custom serialization format, which applications would have to understand. Since controlsErrors was just a convenience method, and it was causing confusing, we are removing it. If you want to get the errors of the whole form serialized into a single object, you can manually traverse the form and accumulate the errors. This way you have more control over how the errors are serialized.
然后 ControlGroup
和 ControlArray
的文档应该更新
另见 https://github.com/angular/angular/issues/6504#issuecomment-171950667
您可以检查 firstNameForm.valid
是否为 false
,然后迭代控制组和控制错误。
NgForm
class 有 errors
属性 因为它继承自 AbstractControlDirective
但那里没有收集嵌套控件的错误。
您正在做模板驱动的表单。请参考这个简单的plunk
<h1>Employee Form</h1>
<form #personForm="ngForm" (submit)="personFormSubmit(personForm)" novalidate>
<div>
<div>
<input id="nameInput" type="text" name="name"
ngControl="name"
required
minlength="2"
maxlength="35"
[(ngModel)]="person.name" />
</div>
</div>
<div>
<button type="submit">Submit</button>
</div>
<div style="color: red">{{validationMessage}}</div>
</form>
然后是控制器:
import { Component } from '@angular/core';
import { FORM_DIRECTIVES, ControlGroup, Control, Validators, FormBuilder, Validator, } from '@angular/common';
import 'rxjs/Rx';
export class Person {
id: number;
name: string;
}
@Component({
selector: 'my-app',
directives: [FORM_DIRECTIVES],
templateUrl: 'app/app.component.html'
})
export class AppComponent {
person: Person;
validationMessage: string;
constructor() {
this.person = new Person();
this.validationMessage = "";
}
personFormSubmit(personForm: ControlGroup) {
if (personForm.valid) {
this.validationMessage = "Form Is Valid";
}
else
{
this.validationMessage = "Form Is Not Valid";
}
}
}
如果您想转向更复杂的动态验证,那么最好转换为模型驱动的表单。与此相同 plunk
我正在尝试检查表单是否有效,以防止在无效时进一步执行。
这是我的表格:
<form (ngSubmit)="updateFirstName(firstNameForm)" #firstNameForm="ngForm" novalidate>
<div class="form-group" ng-class="getCssClasses(formCtrl, formCtrl.firstName)">
<div class="input-group">
<input type="text"
ngControl="firstName"
#firstName="ngForm"
required
minlength="2"
maxlength="35"
pattern_="FIRST_NAME_PATTERN"
[ngModel]="currentUserAccount?.firstName"
(ngModelChange)="currentUserAccount ? currentUserAccount.firstName = $event : null"
placeholder="{{'FIRST_NAME_FORM.NEW_FIRST_NAME'| translate }}"
class="form-control"/>
</div>
<div [hidden]="firstName.valid">
<div *ngIf="firstName?.errors?.minlength" class="control-label">{{'FIRST_NAME_FORM.MIN_LENGTH'| translate}}</div>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary pull-right" [disabled]="buttonDisabled">{{'FIRST_NAME_FORM.SUBMIT'| translate}}</button>
<a [routerLink]="['/dashboard/useraccount']" class="btn btn-link pull-right text-right">{{'FORM_CANCEL' | translate}}</a>
</div>
</form>
但是,当我提交无效表单时,我注意到在控制台中 NgForm
的有效属性是 true
...
updateFirstName(firstNameForm) {
console.log(firstNameForm);//the valid attribute of firstNameForm is true...
}
谁能告诉我为什么会这样?
这是预期的行为
我在 2.0.0-alpha.46 (2015-11-11) 的更改日志中找到
Previously, the controlsErrors getter of ControlGroup and ControlArray returned the errors of their direct children. This was confusing because the result did not include the errors of nested children (ControlGroup -> ControlGroup -> Control). Making controlsErrors to include such errors would require inventing some custom serialization format, which applications would have to understand. Since controlsErrors was just a convenience method, and it was causing confusing, we are removing it. If you want to get the errors of the whole form serialized into a single object, you can manually traverse the form and accumulate the errors. This way you have more control over how the errors are serialized.
然后 ControlGroup
和 ControlArray
的文档应该更新
另见 https://github.com/angular/angular/issues/6504#issuecomment-171950667
您可以检查 firstNameForm.valid
是否为 false
,然后迭代控制组和控制错误。
NgForm
class 有 errors
属性 因为它继承自 AbstractControlDirective
但那里没有收集嵌套控件的错误。
您正在做模板驱动的表单。请参考这个简单的plunk
<h1>Employee Form</h1>
<form #personForm="ngForm" (submit)="personFormSubmit(personForm)" novalidate>
<div>
<div>
<input id="nameInput" type="text" name="name"
ngControl="name"
required
minlength="2"
maxlength="35"
[(ngModel)]="person.name" />
</div>
</div>
<div>
<button type="submit">Submit</button>
</div>
<div style="color: red">{{validationMessage}}</div>
</form>
然后是控制器:
import { Component } from '@angular/core';
import { FORM_DIRECTIVES, ControlGroup, Control, Validators, FormBuilder, Validator, } from '@angular/common';
import 'rxjs/Rx';
export class Person {
id: number;
name: string;
}
@Component({
selector: 'my-app',
directives: [FORM_DIRECTIVES],
templateUrl: 'app/app.component.html'
})
export class AppComponent {
person: Person;
validationMessage: string;
constructor() {
this.person = new Person();
this.validationMessage = "";
}
personFormSubmit(personForm: ControlGroup) {
if (personForm.valid) {
this.validationMessage = "Form Is Valid";
}
else
{
this.validationMessage = "Form Is Not Valid";
}
}
}
如果您想转向更复杂的动态验证,那么最好转换为模型驱动的表单。与此相同 plunk