从组件内部检查 Angular2 表单是否有效 [英] Checking whether an Angular2 form is valid or not from within the component

查看:26
本文介绍了从组件内部检查 Angular2 表单是否有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检查表单是否有效,如果无效则阻止进一步执行.

这是我的表格:

<div class="form-group" ng-class="getCssClasses(formCtrl, formCtrl.firstName)"><div class="input-group"><输入类型="文本"ngControl =名字"#firstName="ngForm"必需的最小长度=2"最大长度=35"pattern_="FIRST_NAME_PATTERN"[ngModel]="currentUserAccount?.firstName"(ngModelChange)="currentUserAccount ? currentUserAccount.firstName = $event : null"placeholder="{{'FIRST_NAME_FORM.NEW_FIRST_NAME'| 翻译}}"class="表单控件"/>

<div [隐藏]="firstName.valid"><div *ngIf="firstName?.errors?.minlength" class="control-label">{{'FIRST_NAME_FORM.MIN_LENGTH'|翻译}}

<div class="form-group"><button type="submit" class="btn btn-primary pull-right" [disabled]="buttonDisabled">{{'FIRST_NAME_FORM.SUBMIT'|翻译}}<a [routerLink]="['/dashboard/useraccount']" class="btn btn-link pull-right text-right">{{'FORM_CANCEL' |翻译}}</a>

</表单>

但是,当我提交无效表单时,我在控制台中注意到 NgForm 的有效属性是 true...

 updateFirstName(firstNameForm) {console.log(firstNameForm);//firstNameForm 的有效属性为真...}

谁能告诉我为什么会这样?

解决方案

您正在做模板驱动的表单.请参考这个简单的plunk

员工表格

<form #personForm="ngForm" (submit)="personFormSubmit(personForm)" novalidate><div><div><input id="nameInput" type="text" name="name"ngControl =名称"必需的最小长度=2"最大长度=35"[(ngModel)]="person.name"/>

<div><button type="submit">提交</button>

<div style="color: red">{{validationMessage}}</div></表单>

然后是控制器:

import { Component } from '@angular/core';导入 { FORM_DIRECTIVES, ControlGroup, Control, Validators, FormBuilder, Validator, } from '@angular/common';导入 'rxjs/Rx';导出类人{身份证号码;名称:字符串;}@成分({选择器:'我的应用',指令:[FORM_DIRECIVES],templateUrl: 'app/app.component.html'})导出类 AppComponent {人:人;验证消息:字符串;构造函数(){this.person = new Person();this.validationMessage = "";}personFormSubmit(personForm: ControlGroup) {如果(personForm.valid){this.validationMessage = "表单有效";}别的{this.validationMessage = "表单无效";}}}

如果您想转向更复杂的动态验证,那么最好转换为模型驱动的表单.就像这个 plunk

I am trying to check whether a form is valid or not to prevent further execution if it is not.

Here is my form:

<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>

However, when I submit an invalid form, I notice in the console that the valid attribute of NgForm is true...

 updateFirstName(firstNameForm) {
   console.log(firstNameForm);//the valid attribute of firstNameForm is true...
 }

Can anyone please let me know why this is the case?

解决方案

You are doing template driven forms. Please refer to this simple 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>

and then the controller:

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";
        }
    }

}

If you want to move to more complex dynamic validation then it would be better to convert to Model driven Forms. As with this plunk

这篇关于从组件内部检查 Angular2 表单是否有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆