Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2: Validate form without defining error messages at each input?

Tags:

angular

I want validate form in angular2. I learn some document, and it will be define like this:

<form [ngFormModel]="form">
        <input type="text" ngControl="username" />

        <p *ngIf="username.pending">Fetching data from the server...</p>

        <div *ngIf="username.dirty && !username.valid && !username.pending">
          <p *ngIf="username.errors.required">Username is required.</p>
          <p *ngIf="username.errors.startsWithNumber">Your username can't start with a number</p>
          <p *ngIf="username.errors.usernameTaken">This username is taken</p>
        </div>

        <button (click)="submitData()" [disabled]="!form.valid" class="btn btn-primary">Sumbit data</button>
</form>
constructor(private builder: FormBuilder) {

    this.username = new Control(
        "", 
        Validators.compose([Validators.required, UsernameValidator.startsWithNumber]),
        UsernameValidator.usernameTaken
    );

    this.form = builder.group({
        username:  this.username
    });
}

With each input I need to define many error messages. I think it's not good.
I want like jquery.validate, I just define input and the error messages will be auto render, like this

<input required name="username" maxlength='8' pattern="^(?!\s|.*\s$).*$" ...> 
like image 685
ThuyNguyen Avatar asked Mar 22 '16 03:03

ThuyNguyen


People also ask

How can you validate that a field of an angular form is already edited by the user?

You can choose to write your own validator functions, or you can use some of Angular's built-in validators. The same built-in validators that are available as attributes in template-driven forms, such as required and minlength , are all available to use as functions from the Validators class.

Which form needs custom validator directive that wrap validation function for form validation?

Reactive forms define custom validators as functions that receive a control to validate. Template-driven forms are tied to template directives, and must provide custom validator directives that wrap validation functions.


1 Answers

To reduce your code one approach could be to write a component.

Which will handle all the condition checkings and error messages

This guy did a nice job here of implementing and explaining it.


HTML with Component would look like this

<input ngControl="email" id="email" />
<control-messages control="email"></control-messages>

and all the dirty work would go inside control-messages component.

like image 61
Ankit Singh Avatar answered Oct 16 '22 05:10

Ankit Singh