Reputation: 539
I have a form with 3 value.
this.testForm = this.formBuilder.group(
{
beginDate: ['', [Validators.required]],
endDate: ['', [Validators.required]],
username: ['', [Validators.required]],
},
{ }
);
I want to put a specific validator for each value so beginDate should be 01.xx.xxxx (should always be the first of the month) endDate should be 25.xx.xxxx (should always be the 25 of the month) username should start with the 'p' letter.
What is the better way to do that ? I can create a validators and check with if/else but it isn't really pretty:
this.testForm = this.formBuilder.group(
{
beginDate: ['', [Validators.required]],
endDate: ['', [Validators.required]],
username: ['', [Validators.required]],
},
{ validator: this.checkValue}
);
Is it a better way to have a validator for each value of my fromgroup ?
Upvotes: 0
Views: 448
Reputation: 10790
You can try a custom validator like below.
function dayOfMonthValidator(date: number): ValidatorFn {
return (control: AbstractControl): {
[key: string]: boolean
} | null => {
let { value } = control;
if (Object.prototype.toString.call(control.value) !== "[object Date]")
value = Date.parse(value);
return value.getDate() === date
? null
: { "dayOfMonth": true }
};
}
and use it like below :
this.testForm = this.formBuilder.group(
{
beginDate: ['', [Validators.required,this.dayOfMonthValidator(1)]],
endDate: ['', [Validators.required,,this.dayOfMonthValidator(25)]],
username: ['', [Validators.required]],
},
);
Upvotes: 1