简体   繁体   中英

Why my min and max validation is not firing?

I have the template like below:

<form class="form" [formGroup]="configWeightage">
  <div class="example-container">
    Enter value in between 0 to 100    <mat-form-field>
      <input
        matInput
        type="number"
        min="0"
        max="100"
        class="example-right-align"
        [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

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.

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