0

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

2
  • 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? Commented 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. Commented Sep 14, 2020 at 12:05

1 Answer 1

1

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> 
Sign up to request clarification or add additional context in comments.

1 Comment

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?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.