1

I am unable to validate for a minimum number on a material input, even though I can successfully validate for required.

<input min="0.01" matInput type="number" placeholder="Amount" style="width: 49%;" [formControl]="numberControl" name="amount"
            [(ngModel)]="amount" required>
  <mat-hint>
     <strong>Available cash: {{selectedMovementFrom?.portfolioValue | currency: 'GBP': 'symbol'}}</strong>
  </mat-hint>

  <mat-error *ngIf="numberControl.hasError('min')">
    Amount cannot be negative.
  </mat-error>

  <mat-error *ngIf="numberControl.hasError('required')">
    Please enter amount.
  </mat-error>

I have also tried checking for validation by referencing the errors object like so:

<mat-error *ngIf="numberControl.errors?.min">
   Amount must be greater than £0.00
</mat-error>

However this also does not display the error, having checked the docs I'm still non-the-wiser.

Any pointers or obvious things I've missed?

m.edmondson
  • 30,382
  • 27
  • 123
  • 206

2 Answers2

0
import { Directive } from '@angular/core';
import { NG_VALIDATORS, AbstractControl, ValidatorFn, Validator, FormControl } from '@angular/forms';
@Directive({
  selector: '[appMinAmountValidator] [ngModel]',
  providers: [
    { provide: NG_VALIDATORS, useExisting: MinAmoutValdiatorDirective, multi: true }
  ]
})
export class MinAmoutValdiatorDirective implements Validator{

  validator: ValidatorFn;
  constructor() {
    this.validator = validateminAmount();
  }
  validate(c: FormControl) {
    return this.validator(c);
  }

}



// validation function
function validateminAmount() : ValidatorFn {
  return (c: AbstractControl) => {

    let isValid = c.value >0;

    if(isValid) {
      return null;
    } else {
      return {
        isminAmountValid: {
          valid: false
        }
      };
    }

  }
}
Sreekar Sree
  • 404
  • 5
  • 14
0

Give it like this:

 <input [min]="0.01" matInput type="number" placeholder="Amount" 
 style="width: 49%;" [formControl]="numberControl" name="amount"
        [(ngModel)]="amount" required>
Anj D
  • 92
  • 3