I have validation when a user is unable to type in letters and can only type in numbers. However, a user is able to copy and paste letters into the input. I need assistance in preventing this from happening. I'm using the function below keyPressNumbersWithDecimal
prevents typing letters but this doesn't prevent a user from copying and pasting letters into it. I am not sure how to do this and looking for help with a possible solution to this.
html
<div >
<mat-form-field appearance="legacy" floatLabel="always">
<mat-label>Breakfast</mat-label>
<input
matInput
type="text"
placeholder="0.00"
formControlName="bfastAmount"
(keypress)="keyPressNumbersWithDecimal($event)"
/>
<span matPrefix>$ </span>
<mat-error *ngIf="pricingSFSPForm.controls['bfastAmount'].errors?.pattern"
>Please provide a valid amount.</mat-error>
</mat-form-field>
</div>
ts
keyPressNumbersWithDecimal(event: {which: any; keyCode: any; preventDefault: () => void}) {
var charCode = event.which ? event.which : event.keyCode;
if (charCode !== 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
event.preventDefault();
return false;
}
return true;
}
CodePudding user response:
If you want to prevent all action when paste,try to use (paste)="" event and preventDefault and stopPropagation with this way
<mat-form-field appearance="legacy" floatLabel="always">
<mat-label>Breakfast</mat-label>
<input
matInput
type="text"
placeholder="0.00"
formControlName="bfastAmount"
(paste)="preventPaste($event)" // add this event binding
(keypress)="keyPressNumbersWithDecimal($event)"
/>
<span matPrefix>$ </span>
<mat-error *ngIf="pricingSFSPForm.controls['bfastAmount'].errors?.pattern"
>Please provide a valid amount.</mat-error>
</mat-form-field>
</div>
ts
preventPaste(event){
event.preventDefault();
event.stopPropagation();
}
CodePudding user response:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/onpaste
Check docs. It's applicable for input HTML element:
<div >
<mat-form-field appearance="legacy" floatLabel="always">
<mat-label>Breakfast</mat-label>
<input
matInput
type="text"
placeholder="0.00"
formControlName="bfastAmount"
(keypress)="keyPressNumbersWithDecimal($event)"
(onpaste)="yourlogichere()"
/>
<span matPrefix>$ </span>
<mat-error *ngIf="pricingSFSPForm.controls['bfastAmount'].errors?.pattern"
>Please provide a valid amount.</mat-error>
</mat-form-field>
</div>
Then, you can simply call the method within component with any custom logic you want.