One of the features on our platform allows users to input a number that will be automatically converted to have a negative sign. However, we want to ensure that users are unable to manually add a negative sign themselves.
We need to find a solution to prevent users from entering a zero after a negative sign. For example, if the current value in the field is -565000, users should not be able to add a zero after the negative sign. Additionally, users should not be able to delete or remove the negative sign manually.
Therefore, inputs such as 0 and any other non-numeric characters should not be allowed.
For instance, if the input is currently -900, and a user attempts to move their cursor after the negative sign and enter 0, or type letters like 'a', these actions should be prevented.
<mat-form-field *ngIf="hasCashContribution === 'no'" appearance="fill" class="deal-form-date-picker opacity87" [ngClass]="{'enabled-input': hasCashContribution === 'no'}" style="padding-right: 16px;">
<mat-label [ngClass]="{'alter-text-color': hasCashContribution === 'no'}">Payment</mat-label>
<input matInput
[(ngModel)]="cashContribution"
class="alter-text-color"
mask="separator.0"
thousandSeparator=","
[allowNegativeNumbers]="true"
oninput="return event.target.value = event.target.value.replace(/[^0-9]/g,'')"
(input)="onInput($event)"
readonly
>
<span matPrefix class="alter-text-color" *ngIf="hasCashContribution === 'no'">$</span>
</mat-form-field>
//prevent 0 inputs
onInput(event: Event) {
const inputElement = event.target as HTMLInputElement;
const inputValue = inputElement.value;
if (event instanceof KeyboardEvent) {
const key = event.key;
// Check if input starts with a negative sign and a non-number key was pressed
if (inputValue.startsWith('-') && !/^-?[0-9]/.test(key)) {
event.preventDefault();
}
} else if (inputValue === '0' || /^0[^0-9]/.test(inputValue)) {
inputElement.value = '';
} else {
const numericValue = parseFloat(inputValue.replace(/,/g, ''));
if (!isNaN(numericValue)) {
this.cashContribution = -numericValue;
}
}
}