验证Angular 2中的表单

时间:2016-08-01 09:49:25

标签: typescript angular

我试图在用户尝试提交表单时显示客户端错误我检查验证器,如果它不符合验证规则它在输入字段周围显示红色框。这样做的好方法是什么?怎么办?

HTML

<button type="button" class="btn-u pull-right margin-bottom-10" data-toggle="modal" data-target="#myModal"><span class="fa fa-plus" aria-hidden="true"></span> Invite User</button>

<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">

        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                <h4 class="modal-title">Invite User</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" id='myForm' role="form" [ngFormModel]="InviteUserForm">
                    <div class="input-group margin-bottom-20">
                        <span class="input-group-addon"><i class="fa fa-user"></i></span>
                        <input type="text" [(ngModel)]='inviteUser.username' class="form-control" ngControl="username">
                    </div>

                    <div class="input-group margin-bottom-20">
                        <span class="input-group-addon"><i class="fa fa-envelope"></i></span>
                        <input type="email" required [(ngModel)]='inviteUser.email' class="form-control" ngControl="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$">
                    </div>

                    <div class="input-group margin-bottom-20">
                        <span class="input-group-addon"><i class="fa fa-glass"></i></span>
                        <select [(ngModel)]='inviteUser.partnerId' class="form-control" ngControl="partner">
                            <option>Select one</option>
                            <option *ngFor="let partner of _partners" value={{partner.Id}}>
                                {{partner.Name}}
                            </option>
                        </select>

                    </div>

                </form>
                <button type="button" class="btn-u btn-u-default margin-right-5" data-dismiss="modal">Close</button>
                <button type="button" [disabled]="!InviteUserForm.valid" class="btn-u pull-right" (click)="Invite(inviteUser)" data-dismiss="modal">Invite</button>
            </div>

        </div>
    </div>

</div>

成分

import { Component, Inject } from '@angular/core';
import { NgForm }    from '@angular/forms';
import { FORM_PROVIDERS, ControlGroup, FormBuilder, Validators, Control} from '@angular/common';
import {UserService} from '../../services/user.service';
import {OnInit} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import { Router }  from '@angular/router';
import { HttpHelper} from '../../utils/httphelper.utils';
import 'rxjs/Rx';
import {InviteModel} from '../../models/invite.model';

import {LocalStorageService} from '../../services/localStorage.service';
@Component({
    selector: 'invite-user',
    templateUrl: '../../app/components/user/invite-user.html',
    providers: [UserService, HttpHelper, LocalStorageService]
})

export class InviteUserComponent {
    InviteUserForm: ControlGroup;
    private _partners: Observable<any[]>;
    private name: string;
    private email: string;
    private partner: number;
    private _data: Observable<any[]>;
    inviteUser: InviteModel;

    constructor(
        @Inject(FormBuilder) public formBuilder: FormBuilder,
        @Inject(UserService) private _userService: UserService,
        @Inject(LocalStorageService) private _localStorageService: LocalStorageService) {

        this.inviteUser = new InviteModel();
        this.InviteUserForm = this.formBuilder.group({
            'username': new Control('', Validators.required),
            'email': new Control('', Validators.compose([Validators.pattern('[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$'), Validators.required])),
            'partner': new Control('', Validators.required)
        });
    }
    ngOnInit() {
        this._userService.partners()
            .subscribe(data => this._partners = data,
            error => {
                console.log("error while retriving partners");
                this._userService.handleError(error);
            }
            );
    }

    Invite(inviteUser) {
        console.log(inviteUser);
        this._userService.inviteUser(inviteUser)
            .subscribe(data => {
                console.log(data);
                this._data = data;
                this.inviteUser = new InviteModel();
            },
            error => {
                console.log("error while retriving partners");
                this._userService.handleError(error);
            },
            () => {
                this._localStorageService.setValue('notifications', 'Info Are You sure to Delete this Entry');
                this.inviteUser = new InviteModel();
            }
        );
    }
}

1 个答案:

答案 0 :(得分:1)

您只需为其添加css class,angular2会自动为您处理。{p>

如果您正在进行任何自定义事项或自定义验证,则必须确保相应地添加class

参考:https://angular.io/docs/ts/latest/guide/forms-deprecated.html

.ng-valid[required] {
  border-left: 5px solid #42A948; /* green */
}

.ng-invalid {
  border-left: 5px solid #a94442; /* red */
}