用户填写表格Angular 2时检查表单验证

时间:2016-12-05 03:19:03

标签: angular typescript angular2-template

我使用

创建了一个带验证检查的表单
import { FormGroup, Validators, FormControl } from "@angular/forms";

目前我有Submit button [disabled],直到表格填写正确。如果表单有效,我向用户显示的唯一方法是在表单字段无效时在输入中显示红色。

enter image description here

我想向用户显示一条错误消息,告诉他们出了什么问题。

Angular2中是否有内容显示错误消息或输入字段无效的原因?或者我是否需要为每个表单字段构建自定义错误消息?如果是这样,我将如何检查每个输入字段,让我们说当有人从相应字段离开焦点时。因此,如果他们离开输入字段并且它无效,那么我可以显示一条消息,告诉他们这是无效的,为什么?

我有一种方法来显示消息,我只需要想出一种获取和错误消息的方法。换句话说,从表格中产生文本为何无效。

示例

Please provide a valid mobile number

代码

REGEX

  ngOnInit() {
        this.personalForm = new FormGroup({
            email : new FormControl(this.auth.user.email,Validators.required ),
            first_name: new FormControl(null,[
                Validators.required,
                Validators.pattern("^[a-zA-Zñáéíóúü']{1,30}$")
            ]),
            middle_name: new FormControl(null,[
                Validators.required,
                Validators.pattern("^[a-zA-Zñáéíóúü']{1,30}$")
            ]),

            last_name: new FormControl(null,[
                Validators.required,
                Validators.pattern("^[a-zA-Zñáéíóúü']{1,30}$")
            ]),

            dob : new FormControl (null, [
                Validators.required,
                Validators.pattern("[1][9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]|[2][0][0-9][0-9]-[0-9][0-9]-[0-9][0-9]")
            ]),
            mobile_phone: new FormControl(null, [
                Validators.required,
                Validators.pattern("[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]|[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]")
            ]),
            home_phone: new FormControl(null, [
                Validators.required,
                Validators.pattern("[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]|[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]")
            ]),

            business_phone: new FormControl(null, [
                Validators.required,
                Validators.pattern("[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]|[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]")
            ]),
            fax_number: new FormControl(null, [
                Validators.required,
                Validators.pattern("[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]|[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]")
            ]),
            ssn: new FormControl(null, [
                Validators.required,
                Validators.pattern("[0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]|[0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]|[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]")
            ])
        });
    }

有效布尔/处理表单数据

save(model: Personal, isValid: boolean) {
        if (!isValid) {
            console.log('Personal Form is not valid');
            console.log(model, isValid);
        } else {
            console.log('Personal Form is valid');
            console.log(model, isValid);
            let headers = new Headers();
            headers.append('Content-Type', 'application/json');
            return this.http
                .post('http://localhost:4200/api/updateProfile',
                    model,
                    {headers: headers})
                .map((res: Response) => res.json())
                .subscribe((res) => {
                    //do something with the response here
                    console.log(res);
                });
        }
    }

表格

<form [formGroup]="personalForm" novalidate (ngSubmit)="save(personalForm.value, personalForm.valid)">
    <div class="row">
        <div class="col-sm-12 col-md-12 col-lg-12">
            <div class="card card-inverse card-success">
                <div class="card-header">
                    <strong>Personal Information</strong>
                </div>
                <div class="card-block">
                    <div class="row">
                        <div class="form-group col-sm-12 col-md-12">
                            <label for="email">Email</label>
                            <div class="input-group">
                                <span class="input-group-addon"><i class="fa fa-envelope"></i>
          </span>
                                <input type="text" class="form-control" id="email" formControlName="email" placeholder="{{personal.email}}"readonly>
                            </div>
                            <div class="alert alert-danger" *ngIf="!personalForm.controls.email.valid && submitted ">
                                *Email is required.
                            </div>
                        </div>
                    </div>

1 个答案:

答案 0 :(得分:1)

<强>摘要

要访问FormGroup input字段,您可以使用syntax访问您创建的controls

this.FormGroupName.get('ControlName').status

这将返回VALIDINVALID

就我而言,这就是它的完成方式,

示例

导入正确的包

import {FormGroup, Validators, FormControl } from "@angular/forms";
import {INVALID, VALID} from "@angular/forms/src/model";

创建FormGroup

personalForm: FormGroup;

创建FormControl

 ngOnInit() {
        this.personalForm = new FormGroup({
            first_name: new FormControl(null,[
                Validators.required,
                Validators.pattern("^[a-zA-Zñáéíóúü']{1,30}$")
            ]),
   });
}

在您希望FormControlName进行检查时,将form添加到functionerror进行通话。

<input (blur)="firstNameValidate('*First Name Required', 'Use 1-30 letters to spell your name.')" type="text" class="form-control" placeholder="Enter first name" id="first_name" formControlName="first_name">

检查VALIDINVALID

firstNameValidate(ErrorTitle, ErrorMessage) {
        if (this.personalForm.get('first_name').status == VALID) {
            this.getSuccess("First Name Entered", "First name entered correctly");
        } else {
            this.toastWarning(ErrorTitle, ErrorMessage);
        }
    }

调用错误

在我的情况下,我决定在toast中显示我的错误。因此,我使用blur来跟踪用户何时离开input字段。当用户离开input字段时,系统会调用firstNameValidate()函数,并根据值toastVALID显示正确的INVALID。取决于response这两个functions中的一个被解雇。

toastWarning(ErrorTitle, ErrorMessage) {
        var toastOptions:ToastOptions = {
            title: ErrorTitle,
            msg: ErrorMessage,
            showClose: true,
            timeout: 7000,
            theme: 'bootstrap',
            onAdd: (toast:ToastData) => {
                console.log('Toast ' + toast.id + ' has been added!');
            },
            onRemove: function(toast:ToastData) {
                console.log('Toast ' + toast.id + ' has been removed!');
            }
        };
            this.toastyService.warning(toastOptions);
        }

    getSuccess(SuccessTitle, SuccessMessage) {
        var toastOptions:ToastOptions = {
            title: SuccessTitle,
            msg: SuccessMessage,
            showClose: true,
            timeout: 5000,
            theme: 'bootstrap',
            onAdd: (toast:ToastData) => {
                console.log('Toast ' + toast.id + ' has been added!');
            },
            onRemove: function(toast:ToastData) {
                console.log('Toast ' + toast.id + ' has been removed!');
            }
        };
        this.toastyService.success(toastOptions);
    }

然后,用户会看到正确的toast / message

<强>成功

enter image description here

警告

enter image description here