使用Angular 2和.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 file :: [编辑]

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

运行代码时,我的控制台向我显示了此错误::

错误类型:无法读取未定义的属性'有效' 在Object.view_addcomponent_0._co [AS UpdateDirectives](ng:///appmodule/addcomponent.ngfactory.js:391:69) 在object.debugupdatedirectives [as Updatedirectives]

我正在进行服务器端验证,因此我无法弄清楚此代码有什么问题...

我正在使用此链接作为参考:: http://www.carlrippon.com/?p = 720

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

您的表格中缺少

相关内容

  • 没有找到相关文章

最新更新