Stop allowing the entry of zero after a minus sign

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;
      }
    }
  }

Answer №1

Initially, the input form in your script is set to readonly, preventing user inputs.

To enable user input, you can modify the oninput event in your <input> form by using the code snippet below:

onkeydown="if (!(/([0-9]|Arrow(Down|Up|Left|Right)|Backspace)/).test(event.key) || ([0,1].includes(event.target.selectionStart) && (event.key == 0)) || (event.target.selectionStart == 1 && event.key == 'Backspace')) {event.preventDefault()}"

Your updated form will look like this:

<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"
        onkeydown="if (...)" // Code snippet
        (input)="onInput($event)"
    />
    <span matPrefix class="alter-text-color" *ngIf="hasCashContribution === 'no'">$</span>
</mat-form-field>

This should resolve the issue at hand.

However, instead of manipulating values to be negative using JavaScript, consider adding a negative sign (-) before the input form, possibly through a ::before pseudo-element.

Furthermore, it seems unnecessary to include the [allowNegativeNumbers] attribute.

Lastly, take note that users can still paste various characters into the input field unless further restrictions are implemented.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The jasmine and protractor combination couldn't locate the specified element using its tagname

Why does my test keep failing in Protractor when trying to find the element by tag name? it('should display the test component', async () => { await browser.get('/trade') element(by.tagName(('test-component'))).isP ...

Resolving the issue: "How to fix the error "Credentials are not supported if the CORS header 'Access-Control-Allow-Origin' is '*' in React?"

Recently, I encountered some CORS issues while using a third party API in my front-end application. After reaching out to the API maintainers, they lifted the CORS control by adding a * to Access-Control-Allow-Origin, which seemed like the perfect solution ...

Tips for fixing the error message of "Cannot access value property of null"

I am facing an issue in my Angular application where I need to conditionally display a div based on certain criteria. Initially, when the page loads, there are no console errors and the div is not shown due to the ngIf condition being false. However, upo ...

Switching between play and pause for the video element using a component for the child

Trying to toggle the play/pause of a child video by clicking on a parent div can be challenging, especially when dealing with multiple instances of the same div and video. A normal function may only work for one specific video, as mentioned by @ken. I hav ...

What is the best way to insert a row into a JavaScript table while incorporating a cell that utilizes the datepicker function in jQuery?

Currently, I am working on a javascript function: function addItem(tableID){ var table = document.getElementById(tableID); var rowCount = table.rows.length; var row = table.insertRow(rowCount); var cell1 = row.insertCell(0); var el ...

Is there a way to efficiently update the template within the *ngFor directive when working with an array of objects in Angular 2/

My Json Object is structured as follows: var obj = { "TimSays":"I can Walk", "RyanSays":"I can sing", "MaxSays":"I can dance", "SuperSays":"I can do it all" } To iterate through this object in the template, I am using a pipe helper due to ...

Creating a TypeScript function that can dynamically assign values to a range of cells within a column, such as AD1, AD2, AD3, and so on

Hello there I'm currently working on a function that will dynamically assign values to the column range of AE to "AD" + i. However, when I use the function provided below, it only writes AD5 into the first 5 columns instead of AD1, AD2, AD3, and so o ...

Transforming a material-ui component from a class to a function

Currently, I am in the process of learning material-ui, and it seems that most of the code examples I come across are based on classes. However, the new trend is moving towards using functions instead of classes due to the introduction of hooks. I have be ...

Creating distinct short identifiers across various servers

Utilizing the shortid package for creating unique room IDs has proven effective when used on a single server. However, concerns arise regarding the uniqueness of IDs generated when utilized across multiple servers. Is there a method to ensure unique ID g ...

Creating a dynamic circle that expands in size based on the duration the user presses down (using Java Script)

I have a fun challenge for you! I want to create a growing circle on a canvas based on how long you hold your mouse button. Currently, I can draw a fixed width circle where my mouse was when I clicked, but I need it to dynamically change size as you hold t ...

What could be causing the issue with saving form data to local storage in React?

I am facing an issue with the code I have written to store data in local storage. Sometimes it works fine, but other times it saves empty data or erases the previous data when the Chrome window is closed and reopened. Any idea what could be causing this in ...

Failed PHP response when jQuery was called

I'm working on a project that involves two files: one PHP and one HTML. The HTML file acts as the user interface where users input their queries, while the PHP file handles the processing and events before returning the output back to the HTML file. I ...

What are the drawbacks of calling async/await within a fresh Promise() constructor?

I have implemented the async.eachLimit function to manage the maximum number of operations concurrently. const { eachLimit } = require("async"); function myFunction() { return new Promise(async (resolve, reject) => { eachLimit((await getAsyncArray ...

Retrieve both positive and negative reviews using the Steam API

I'm trying to calculate the percentage of positive reviews, but I haven't been able to find the necessary data. I've been using this endpoint to retrieve game information: "", but it only provides the total number of reviews. I am aware of a ...

What is a global variable used for in JavaScript?

Here is the code snippet that I am currently working on: $(".link").each(function() { group += 1; text += 1; var links = []; links[group] = []; links[group][text] = $(this).val(); } ...

Data is not displaying correctly in the Angular Material Table

I'm currently trying to build a mat table based on an online tutorial, but I'm facing a problem where the table appears empty even though I have hard coded data. As someone new to Angular and HTML/CSS, I'm struggling to understand why the ma ...

Searching for results using the .find() method may yield elements that do not meet the specified search criteria

Utilizing the .find() method on my JSON object called records: [ { "_id": "61f9da9fcc6888f201f722cb", "firstName": "joe", "lastName": "jergen", "email": "<a hre ...

What is the best way to extract a nested array of objects and merge them into the main array?

I've been working on a feature that involves grouping and ungrouping items. A few days ago, I posted this question: How can I group specific items within an object in the same array and delete them from the core array? where some helpful individuals ...

modify the tr element within a jQuery context

I am attempting to convert a "yes" to a select dropdown that allows users to choose between yes and no. The HTML structure is as follows: <tr> <td>text</td> <td>no (needs to be changed via JS)</td> <td><a href="#"&g ...

Encountering an excessive number of re-renders due to attempting to display a FlatList component

I am attempting to showcase a flatList of numbers similar to this: (view image example) In order to achieve this, I created an array of objects with a numberName and a key using a loop: const number = 5; let [numbers, setNumbers] = useState([]); let nums ...