Form validation Angular 4 | multi-field validation | Set error on empty Field depending on other field
Form validation Angular 4 | multi-field validation | Set error on empty Field depending on other field
I have a form where two fields ('From date' and 'To Date') are there along with other fields.
Requirement:
User can provide only 'From Date'
If both date are given 'From date' must NOT be greater than 'To Date'; if given 'To Date' will be underlined with Red.
If one provides 'To Date' only, then the 'From Date' will be underlined with Red.
To do this I used a frombuilder 'SrchForm' like this:
myForm(){
this.srchGrp = this.SrchForm.group({
//other FormcontrolNames
from_date : '', // from_date controlname for 'From Date' field
to_date : '', // to_date controlname for 'To Date' field
}, {validator: this.fromNtoValidate('from_date', 'to_date')})
}
And,
fromNtoValidate(from_date, to_date){
return (group: FormGroup)=>{
let fromdate = group.controls['from_date'],
let todate = group.controls['to_date'],
if(formdate.value && todate.value){ // if both date provided
if (formdate.value > todate.value){
return todate.setErrors({'incorrect' : true});
}
}
if(!formdate.value && todate.value){ // **if Todate provided only
console.log("only Todate Given");
return fromdate.setErrors({'incorrect' : true});
}
}
}
**if Todate provided only
part is failing to red-mark the Form Date
field though it's printing only Todate Given
as expected. If I try to set error on todate
instead of 'fromdate', then it's working fine but not working on fromdate
.
**if Todate provided only
Form Date
only Todate Given
todate
fromdate
Please suggest me what to do here and mark where I'm doing wrong?
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
This can help you a little. stackoverflow.com/questions/45262323/…
– iPaul
Jul 2 at 10:31