如何在Angular 2中实现表单输入验证

时间:2016-12-14 11:49:57

标签: angular

如何通过Angular2 FormsModule提交这些输入以在提交时显示诸如“名称是必需的”之类的消息(因此提交按钮被禁用,直到内部有名称)?

<form class="">
    <div>
        <p>Name:</p>
        <input type="text">
    </div>
    <div class="link-input">
        <p>City:</p>
        <input type="text">
    </div>

    <button 
        (click)="submitForm()">
        Submit
    </button>
</form>

2 个答案:

答案 0 :(得分:2)

请遵循以下示例:

<form [formGroup]="registerForm" (ngSubmit)="submitForm(registerForm)"   novalidate>
    <div>
        <p>Name:</p>
        <input type="text">
        </div>
        <div class="link-input">
            <p>City:</p>
            <input formControlName="username" type="text">
                <em for="username" [hidden]="showError(registerForm.controls.name)" class="invalid">        You left this field blank or email format is not correct</em>

            </div>

            <button type="submit" >Submit</button>
</form>

组件:

showError(field: FormControl){
        if(!field)
            return true;
        return field.valid || (field.pristine && !field.touched && !this.submitted)
    }

submitForm(f: NgForm) {
    this.submitted = true;
    if(!f.valid)
        return;
}

答案 1 :(得分:0)

只需添加检查表单是否有效,否则禁用按钮

<button type="submit" class="btn btn-danger" [disabled]="!f.valid">Save to List</button>