I have a field named LDC and other two fields on form are limit1 and limit2. I want to show an error message if limit1 or limit2 is greater than LDC also if limit1+limit2 is greater than LDC. I tried writing a custom validator but it somehow doesn't work. I read about rxwebvalidators is it possible to write custom error mesaages for these validators? any help would be appreciated. thanks in advance
- Add the custom validator to the FormGroup containing your FormControls. This way you can read the values of all controls necessary for your validation. Also, you should provide minimal code samples or we can't really help you further. What does your Form look like? What code have you tried that does not work?pascalpuetz– pascalpuetz2020-09-14 12:04:30 +00:00Commented Sep 14, 2020 at 12:04
- Use 'input' even to perform the validations on real time when the form fields are updated, or use 'FormGroup.valueChanges()' which returns an observable that you can subscribe to.elonaire– elonaire2020-09-14 12:05:09 +00:00Commented Sep 14, 2020 at 12:05
Add a comment |
1 Answer
One simple way is to declare a boolean as :
displayError = false; then using valueChanges foreach field:
limit1.valueChanges().pipe( distinctUntilChanged() ).subscribe(value => { if (value + limit2.value < LDC) { // i dont know what is LDC this.displayError = true; } else { this.displayError = false; } }); same for limit2 (assuming these are FormControls).
then, in your template, you can use ngIf directive as:
<div> <input .... > <span *ngIf="displayError">Error message</span> </div> 1 Comment
Ruby S
Hi your solution worked. I want to save that subscribed value in other variable and I did like this.changedLimit1 = value; but when I am debugging I can see changedLimit1 is always undefined. is there any other way to assign the value?