使用 angular 2 和 .net core web api 的服务器端验证

server side validation using angular 2 and .net core web api

我的html代码::

<form novalidate [formGroup]="personForm" (ngSubmit)="onSubmit()" class="form-horizontal">
    <div class="form-group" [ngClass]="{'has-error':!personForm.controls.username.valid && personForm.controls.username.touched}">
            <div class="col-sm-6">
                <label class="control-label" for="username">Username</label><span>*</span>
                <input type="text" class="form-control" id="username" formControlName="username" />
            </div>
        </div>
        <div class="alert alert-danger" role="alert"
             *ngIf="!personForm.controls.username.valid && personForm.controls.username.touched">
            You must enter a username
        </div>
</form>

和 ts 文件 :: [已编辑]

import { Component , OnInit } from '@angular/core';
import 'rxjs/Rx';
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { HomeService } from './../Service/home.service'
import { User, Users } from '../Models/xyz'
import {Router} from '@angular/router'
@Component({
    templateUrl: './add.component.html',
    styleUrls:['./form.component.css'],
})

export class AddComponent implements OnInit {
    //users: IUser;
    personForm: FormGroup;
    successfulSave: boolean;
    errors: string[];
    afterAdded = false;
    currentUser: Users;
    timer: any;
    msg = "";

    pageTitle = 'Add User';

    constructor(private _homeService: HomeService, private _http: Http, private _router: Router, private fb: FormBuilder) {

        this.currentUser = new Users();
    }
    ngOnInit(): void{
        clearTimeout(this.timer);
        this.personForm = this.fb.group({
            username: ['', Validators.required],
            firstName: ['', Validators.required],
            lastname: ['', Validators.required],
            email: ['', Validators.required],
            password: ['', Validators.required],
            gender: ['', Validators.required]
        });
        this.errors = [];
    }


    onSubmit() {
        if (this.personForm.valid) {
            let headers = new Headers({ 'Content-Type': 'application/json' });
            let options = new RequestOptions({ headers: headers });
            let person = {
                username: this.personForm.value.username,
                firstName: this.personForm.value.firstname,
                lastname: this.personForm.value.lastname,
                email: this.personForm.value.email,
                password: this.personForm.value.password,
                gender: this.personForm.value.gender,
            };
            this.errors = [];
            this._http.post('/api/person', JSON.stringify(person), options)
                .map(res => res.json())
                .subscribe(
                (data) => this.successfulSave = true,
                (err) => {
                    this.successfulSave = false;
                    if (err.status === 400) {
                        // handle validation error
                        let validationErrorDictionary = JSON.parse(err.text());
                        for (var fieldName in validationErrorDictionary) {
                            if (validationErrorDictionary.hasOwnProperty(fieldName)) {
                                this.errors.push(validationErrorDictionary[fieldName]);
                            }
                        }
                    } else {
                        this.errors.push("something went wrong!");
                    }
                });
        }
    }
}

当我 运行 我的代码时,我的控制台显示这个错误::

错误类型错误:无法读取未定义的 属性 'valid' 在 Object.View_AddComponent_0._co [as updateDirectives] (ng:///AppModule/AddComponent.ngfactory.js:391:69) 在 Object.debugUpdateDirectives [作为 updateDirectives]

我正在做服务器端验证,所以我不知道这段代码有什么问题...

我正在使用这个 link 作为参考::http://www.carlrippon.com/?p=720

[formGroup]="personForm" (ngSubmit)="onSubmit()"

您的表单中缺少