0
votes

It is starting to get frustrating when working on Model-Driven-Form validation that are still not working for 2 days now.

As I understand, there's still some bugs with Angular2 beta still. I used the example from angular-io at https://angular.io/docs/ts/latest/guide/forms.html and different example at Forms In angular2 . Two programmers here at my company told me they both still haven't any form example working either.

Can anyone provide me a working example of validation that I can try out?

2
I wrote a blog post, about model driven forms in Angular2 recently. lukajcb.github.io/blog/angular2/2016/04/02/…Luka Jacobowitz

2 Answers

2
votes

The key is building the control group:

this.form = fb.group({
            "firstName": ['', Validators.required],
            "streetAddress": ['',Validators.required],
            "zip": ['', Validators.compose([zipValidator])],
            "type": ['home']
        });

Here are a few form examples with validation:

http://www.syntaxsuccess.com/angular-2-samples/#/demo/form More info here: http://www.syntaxsuccess.com/viewarticle/forms-and-validation-in-angular-2.0

Here is an example of a dynamic form as well:

http://www.syntaxsuccess.com/angular-2-samples/#/demo/survey http://www.syntaxsuccess.com/viewarticle/dynamic-form-in-angular-2.0

0
votes

Well as you already know there are still some pending issue's related to angular2 forms with validation. But after searching a lot i found few one is working which is posting now as answer -

Firstly For validation you have to use ngControl , also you can use ngModel i.e two way binding of angular2 for getting values of forms no doubt we can use only ngControl for validation and for form values too. but it is good practice to use separate ones.

use ngControl for the validation purpose. there are default validators provide by angular to check validation we can create our custom one too as per need and can use in the validation (ngControl). if we are going to create model driven form i.e we have to create new control for every input by using new Control(). for the Control, control group and validation refer this best artical

here is the basic example of using controls for the form:

this.CreateGroup = fb.group({
            'name': new Control(this.demoInfo.name, Validators.required),
            'password': new Control(this.demoInfo.password, Validators.required),
            'select': new Control(this.demoInfo.select, Validators.required)
        })

Here i have three inputs named name, password,select respectively. and corresponding i have mentioned their values and validators (default validation).

<input type="text" [(ngModel)]='demoInfo.name' ngControl='name'>

here is how we define ngControl to out HTML side.

Working demo of form in angular2 with validation.