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$).*$" ...>
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With