Instance variable version of customized validated Control
import { Component } from 'angular2/core';
import {
ControlGroup,
AbstractControl,
FormBuilder,
Validators,
Control,
CORE_DIRECTIVES,
FORM_DIRECTIVES
} from 'angular2/common';
@Component({
selector: 'demo-form-with-custom-validations',
directives: [CORE_DIRECTIVES, FORM_DIRECTIVES],
template: `
<div class="ui raised segment">
<h2 class="ui header">Demo Form: with custom validation</h2>
<form [ngFormModel]="myForm"
(ngSubmit)="onSubmit(myForm.value)"
class="ui form">
<div class="field"
[class.error]="sku.touched && !sku.valid">
<label for="skuInput">SKU</label>
<input type="text"
id="skuInput"
placeholder="SKU"
[ngFormControl]="sku"]>
<div *ngIf="!sku.valid" class="ui error message">SKU is invalid.</div>
<div *ngIf="sku.hasError('required')" class="ui error message">
SKU is required.
</div>
<div *ngIf="sku.hasError('invalidSku')" class="ui error message">
SKU must begin with <tt>123</tt>
</div>
</div>
<div *ngIf="!myForm.valid">
Form is invalid.
</div>
<button type="submit" class="ui button">Submit</button>
</form>
</div>
`
})
export class DemoFormWithCustomValidation{
myForm: ControlGroup;
sku: AbstractControl;
/* Adding multiple validators to a single field requires using
Validators.compose which takes an array of validators wrapping
all of the validators and assigning it to a control. The control
is not valid untill all the validations in the array are valid. */
constructor(fb: FormBuilder){
this.myForm = fb.group({
'sku': ['', Validators.compose([
Validators.required,
skuValidator
])]
});
this.sku = this.myForm.controls['sku'];
}//constructor ends here.
onsubmit(value: string): void{
console.log('You submitted value: ', value);
}
}//class DemoFormWithCustomValidation ends here.
/* Custom validation. We are customizing validation using the function
skuValidator given below. We want the sku to begin with numbers 123
so we will make sure in the funciton below that the sku begins with numbers.
The function returns a StringMap<string, boolean> where the key is
"error code" and the value is "true" if the validator fails.
*/
function skuValidator(control: Control): {[s: string]: boolean}{
if(!control.value.match(/^123/)){
return {invalidSku: true};
}
}
No comments:
Post a Comment