Search code examples
angularasp.net-core-webapiserver-side-validation

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


My html code ::

<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>

AND ts file :: [EDITED]

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

When I run my code, my console shows me this error::

ERROR TypeError: Cannot read property 'valid' of undefined at Object.View_AddComponent_0._co [as updateDirectives] (ng:///AppModule/AddComponent.ngfactory.js:391:69) at Object.debugUpdateDirectives [as updateDirectives]

I am doing server-side validation so I can't figure out what is wrong with this code ...

I am using this link as reference::http://www.carlrippon.com/?p=720


Solution

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

    is missing in your form