Aashish Shrestha
Aashish Shrestha

Reputation: 25

How do I validate one value entered in one form control is greater than one entered in another form control in Angular?

I have two form field minAmount and maxAmount in reactive form in Angular. I need to make sure that the maxAmount is greater than minAmount. I've tried using:

 this.form = this.formBuilder.group({
    minAmount: [undefined],
    maxAmount: [undefined, [Validators.min(this.form.get('minAmount').value)]]

  });   

but this doesn't seem to work.

Upvotes: 0

Views: 5922

Answers (2)

Eliseo
Eliseo

Reputation: 57919

you need make a custom validator over the formGroup or a customValidator and check the two values. If only check the minAmount, when you change the max, Angular don't check the values.

If you make a custom validator over the fromGroup, take account that each change in any input of the formGroup, "call" to the validator function

  form = this.formBuilder.group({
    minAmount: [undefined,this.customValidator()],
    maxAmount: [undefined, this.customValidator()]
  }); 

  customValidator()
  {
    return (control:FormControl)=>
    {
      const form=control.parent
      if (form)
      {
        const min=form.get('minAmount');
        const max=form.get('maxAmount');
        return min.value && max.value && +max.value<+min.value?{error:'min malue'}:null
      }
    }
  }

 <div *ngIf="form.get('minAmount')?.errors.error 
          || form.get('maxAmount')?.errors.error">
      error
 </div>

or

  form = this.formBuilder.group({
    minAmount: [undefined],
    maxAmount: [undefined]
  },{validators:this.customValidatorGroup()}); 

  customValidatorGroup()
  {
    return (form:FormGroup)=>{
        const min=form.get('minAmount');
        const max=form.get('maxAmount');
        return min.value && max.value && +max.value<+min.value?{error:'min malue'}:null
    }
  }

  <div *ngIf="form.errors?.error">
        error group
  </div>

Upvotes: 3

user3802184
user3802184

Reputation: 29

Try something like this

  this.form = this.fb.group({
    minAmount: [undefined, Validators.required],
    maxAmount: [undefined, Validators.required]
  }, { validator: findMaxamount }
  );

And create your own validator like

findMaxamount(form: FormGroup){
  const min = form.get('minAmount').value;
  const max = form.get('maxAMount').value;
  return max > min ? true : false;
}

Upvotes: 0

Related Questions