Angular2 Custom Validations All Versions
This draft deletes the entire topic.
Examples
-
Angular 2 has two kinds of custom validators. Synchronous validators as in the first example that will run directly on the client and asynchronous validators (the second example) that you can use to call a remote service to do the validation for you. In this example the validator should call the server to see if a value is unique.
export class CustomValidators { static cannotContainSpace(control: Control) { if (control.value.indexOf(' ') >= 0) return { cannotContainSpace: true }; return null; } static shouldBeUnique(control: Control) { return new Promise((resolve, reject) => { // Fake a remote validator. setTimeout(function () { if (control.value == "exisitingUser") resolve({ shouldBeUnique: true }); else resolve(null); }, 1000); }); }}
If your control value is valid you simply return null to the caller. Otherwise you can return an object which describes the error.
-
constructor(fb: FormBuilder) { this.form = fb.group({ firstInput: ['', Validators.compose([Validators.required, CustomValidators.cannotContainSpace]), CustomValidators.shouldBeUnique], secondInput: ['', Validators.required] }); }
Here we use the FormBuilder to create a very basic form with two input boxes. The FromBuilder takes an array for three arguments for each input control.
- The default value of the control.
- The validators that will run on the client. You can use Validators.compose([arrayOfValidators]) to apply multiple validators on your control.
- One or more async validators in a similar fashion as the second argument.
-
Topic Outline
Parameters
Sign up or log in
Save edit as a guest
Join Stack Overflow
Using Google
Using Facebook
Using Email and Password
We recognize you from another Stack Exchange Network site!
Join and Save Draft