简体   繁体   中英

How to perform min and max validation in angular reactive forms?

I have the following code:

    constructor() { 
this.feedbackForm = new FormGroup({
  suggestedAScore: new FormControl('', [Validators.pattern(/^[0-9]+$/),Validators.required, Validators.maxLength(5), Validators.minLength(5)]),
  minScore: new FormControl('', [Validators.pattern(/^[0-9]+$/),Validators.required,Validators.minLength(1),Validators.maxLength(1)]),
  maxScore: new FormControl('', [Validators.pattern(/^[0-9]+$/),Validators.required,Validators.minLength(1),Validators.maxLength(1)])
});
this.feedbackForm.setValidators(this.minMaxValidator());
 }




public minMaxValidator() : ValidatorFn{
return (group: FormGroup): ValidationErrors => {
  const min = group.controls['minScore'];
  const max = group.controls['maxScore'];
  var changedValue;
  if (min.value && max.value) {
    if (this.prevMinVal && (this.prevMinVal === min.value)) {
      changedValue = max;
      this.errorMessage = 'Max value should be greater than Min value';
    } else {
      changedValue = min;
      this.errorMessage = 'Min value should be lesser than Max value';
    }
    this.prevMinVal = min.value;
    if (min.value >=  max.value) {
      changedValue.setErrors({notEquivalent: true});
    } else {
      min.setErrors(null);
      max.setErrors(null);
    }
  };
 // this.isFeedbackFormValid();
    return;
 }
 };

Here with this code when I enter max value less than min value the error is shown at min not at max.My question is how to highlight the input that entered is wrong.Can anyone please suggest me help.Thanks.

You can have to create custom Validator like this:

const RangeValidator: ValidatorFn = (fg: FormGroup) => {
  const start = fg.get('min').value;
  const end = fg.get('max').value;
  return start !== null && end !== null && parseFloat(start) < parseFloat(end)
    ? null
    : { range: true };
};

In your ts file while creating the form you have to provide Validation on a full form so you get both input value changes

this.formbuilder.group({
      min: [null, [//Your Validation for number/decimal]],
      max: [null, [//Your Validation for number/decimal]]
}, { validator: RangeValidator }))

Why are you creating your own logic of min and max validators when angular provides min and max native validation.

When you set validation in your FormControl so you can just a single condition in your component.hmtl like this

 <mat-error *ngIf="feedbackForm.controls.minScore.hasError('minlength')">
    Your error message here. 
  </mat-error>

I just showed you an example that how can you show errors conditionally using validators .

You can make a css class that make your input red like this

.error{border-color : red}

And inside your html on your input you can do like this

<input type="text" formControl="minScore" [ngClass]="{'error' :(feedbackForm.get('minScore').touched || feedbackForm.get('minScore').dirty) && !feedbackForm.get('minScore').valid }">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM