Home > Net >  Currency validation on mat-input
Currency validation on mat-input

Time:12-14

I am trying to put in validation when a user types in a price if they type in $20.0000 in the input a validation message will appear the form would mark it as invalid. Would this be a regex validation and if so how do you do that? I am not sure how to do this and looking for help with a possible solution to this.

<mat-form-field appearance="legacy" floatLabel="always">
          <mat-label>Breakfast</mat-label>
          <input
            matInput
            type="number"
            
            placeholder="0"
            [formControl]="bfastamountCtrl"
            [value]="bfastamountCtrl.value | number: '1.2-2'"
          />
          <span matPrefix>$&nbsp;</span>
        </mat-form-field>

CodePudding user response:

It seems you use Angular with a reactive form? If so you should either

a. provide a custom Validator for the given field.

b. or use the pattern-validator

Example for a:

const myValidator(control: FormControl) { 
    const value = control.value; 
    if (/* whatever is a invalid value*/) { 
        return /* some object that defined the error */
    }
    return null;
}

and use it like

...
bfastamountCtrl = 
    new FormControl('', [myValidator]
);

Example for b:

...
bfastamountCtrl = 
    new FormControl('', [Validators.pattern("/' your regex-pattern */")
]);
...

CodePudding user response:

I guess you should try this. With pattern you can validate your input control.

<mat-form-field appearance="legacy" floatLabel="always">
      <mat-label>Breakfast</mat-label>
      <input
        matInput
        type="number"
        
        pattern="^\$(\d{1,3}(\,\d{3})*|(\d ))(\.\d{2})?$"
        placeholder="0"
        [formControl]="bfastamountCtrl"
        [value]="bfastamountCtrl.value | number: '1.2-2'"
      />
      <span matPrefix>$&nbsp;</span>
    </mat-form-field>
  • Related