Home > other >  Why my min and max validation is not firing?
Why my min and max validation is not firing?

Time:03-28

I have the template like below:

<form  [formGroup]="configWeightage">
  <div >
    Enter value in between 0 to 100    <mat-form-field>
      <input
        matInput
        type="number"
        min="0"
        max="100"
        
        [formControlName]="weightageValue"
        id="weightage"
        required
      />
    </mat-form-field>
    <mat-error *ngIf="weightageValue.hasError('min(0)')" style="color: red"
      >Please enter greater than 0</mat-error
    >
    <mat-error *ngIf="weightageValue.hasError('max(100)')" style="color: red"
      >Please enter less than 100</mat-error
    >
  </div>
</form>

This is the class file

 import { Component } from '@angular/core';
    import { FormBuilder,FormGroup, Validators,FormControl } from '@angular/forms';
    
    /** @title Form field with prefix & suffix */
    @Component({
      selector: 'form-field-prefix-suffix-example',
      templateUrl: 'form-field-prefix-suffix-example.html',
      styleUrls: ['form-field-prefix-suffix-example.css'],
    })
    export class FormFieldPrefixSuffixExample {
      configWeightage:FormGroup;
      formBuilder : FormBuilder;
      weightageValueControl = new FormControl(['',Validators.required,Validators.min(0),Validators.max(100)]);
      hide = true;  
      constructor(private fb: FormBuilder) {}
      ngOnInit() {
        
       this.configWeightage = this.formBuilder.group(
        {
          'weightageValue' :this.weightageValueControl      
        }
    
       )
      }
    }

I am supposed the fire the error when there is a value NOT in between 0 and 100

But no validation message will be fired

Here is the stack bliz code for the same, so that you can run and fix yourself.

https://stackblitz.com/edit/angular-mat-form-field-dq8ntd?file=app/form-field-prefix-suffix-example.html

CodePudding user response:

There are some errors and typos you should fix in your Stackblitz :

  • Remove brackets from [formControlName]

  • Remove min and max attributes from <input> as you've already specified them using validators

  • Move <mat-error> inside <mat-form-field>

  • For the error condition, you should use formGroupName.get('FormControlName').hasError('validatorName')

  • Remove style="color: red" from <mat-error>, this is already the default style for the error message.

  • Fix the typo this.formBuilder.group to be this.fb.group

    Here is Stackblitz after fixing the above errors.

  • Related