I’m currently using an ion-input element to retrieve input from the user (specifically amount in dollars USD), however I am having a difficult time trying to figure out the best way to approach this where it restricts the amount of decimals and normalizes the amount (i.e $5.0 → $5.00 or $5.201 is not valid and input past $5.20 is not allowed).
Here is my relevant code:
create-listing.page.html
<ion-input type="text" [(ngModel)]="listingPrice" (keyup)="listingPriceValidation($event)" debounce="0"></ion-input>
create-listing.page.ts
listingPriceValidation(event: any) {
// const pattern = new RegExp('^[+-]?[0-9]{1,3}(?:,?[0-9]{3})*\.[0-9]{2}$');
const pattern = new RegExp('^[+-]?[0-9]{1,3}(?:,?[0-9]{3})*(?:\.?([0-9]{1,2})?)?$')
let userInput = this.listingPrice;
let output = "";
if ( pattern.test(this.listingPrice) === true ) {
let holdingNumber : number = 0;
holdingNumber = +userInput;
let output = holdingNumber.toFixed(2);
this.listingPrice = output
} else {
event.preventDefault();
}
}
This code works in that it adds decimals when someone types in a whole number initially, but the UX isn’t really good since it makes the user have to highlight a certain place to edit the dollar amount. Also, the regex for some reasons accepts any input at the “.” place.
Does anyone have any suggestions on how to improve this?
1 post - 1 participant