Reputation: 3109
I want to make a custom validation for angular2. This validation must access another component of the form. Is this possible?
My template
<input type="tekst" id="startDate" name="startDate" [(ngModel)]="model.startDate" #startDate="ngModel" >
<input type="tekst" id="endDate" name="endDate" [(ngModel)]="model.endDate" #endDate="ngModel" customValidator>
My validator
...
@Directive({
selector: '[customValidator][ngModel][customValidator][formControl]',
providers: [
provide : NG_VALIDATORS,
useExisting : forwardRef(() = > CustomValidator),
Multi : true
}]
})
export class CustomValidator impelments Validator {
constructor(){}
validate(c : FormControl) : {[key : string] : any} {
// HOW TO ACCESS startDate CONTROL HERE? OR ITS VALUE? OR THE MODEL
}
Upvotes: 4
Views: 816
Reputation: 3483
You can like
@Directive({
selector: '[customValidator][ngModel][customValidator][formControl]',
providers: [
provide : NG_VALIDATORS,
useExisting : forwardRef(() = > CustomValidator),
Multi : true
}]
})
export class CustomValidator impelments Validator {
constructor(){}
validate(c : FormControl) : {[key : string] : any} {
let control_value= c.value;
// HOW TO ACCESS startDate CONTROL HERE? OR ITS VALUE? OR THE MODEL
}
also refer this link also: custom validator and custom validtor with reverse match
Upvotes: 0
Reputation: 16837
If you want to implement cross validation you should move the validation to the ancestor control.
Then your validate method can look like this:
validate(fg: FormGroup) {
const start = fg.get('startDate').value;
const end = fg.get('enDate').value;
return start !== null && end !== null && start < end
? null
: { range: true };
};
Read more about cross validation here.
Upvotes: 1