Validating Input Field with Regular Expression in JavaScript/TypeScript to Avoid Starting with Zero

I need to create a RegEx for a text field in Angular / TypeScript that limits the user to inputting only a 1-3 digit number that does not start with 0. While it's straightforward to restrict input to just digits, I'm struggling to prevent an input that starts with 0 without breaking the RegEx validation.

<input matInput

  [(ngModel)]="backupIntervalLength"
  (ngModelChange)="onIntervalLengthChange($event)"
  maxLength="3"
  onkeypress="return String.fromCharCode(event.charCode).match(/[^0-9]/g) === null"
  
>

Answer №1

I am not very familiar with Angular, but I can offer a JavaScript solution for your question. Since you did not specify Angular in your question, I will provide code that can easily be translated into Angular if needed.

const userInput = document.getElementById("userInput");

userInput.addEventListener("input", event => {
  const { value } = event.currentTarget;
  
  if (!/^[1-9]\d{0,2}$/.test(value)) {
    event.currentTarget.value = value.slice(0, -1);
  }
});
<input id="userInput" type="number" />

Answer №2

It turns out the solution was simpler than I thought. All it took was a little change in perspective :)

<input matInput

  [(ngModel)]="backupIntervalLength"
  (ngModelChange)="onIntervalLengthChange($event)"
  maxLength="3"
  onkeypress="return String.fromCharCode(event.charCode).match(/[^1-9]?[^0-9]?[^0-9]/g) === null"
  
>

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

What is the best way to remove <a> tags from an XML document?

I'm dealing with <a> tags within an XML file and I need to remove only the <a> tags. For instance: <test>This is a line with <a name="idp173968"></a> tags in it</test> I am unable to use str_replace to replace t ...

Tips for executing a function in jQuery when a Pop up appears

I am currently utilizing the AjaxToolKit:ModelPopUpExtender to generate a popup within an asp.net application. At first, the asp:Panel (which holds the content of the popup) is set as <asp:Panel ID="PanlUpdate" runat="server" CssClass="Popup" align="c ...

Receiving an error message and identifying the specific line number within the catch

try{ cause error } catch(err){ console.log(err.lineNumber) //or console.log(err.line) } The error object has various properties like err.name, err.stack, and err.message, but I have been unable to find a way to log the line number of the error ...

Is it possible to display data on a webpage without using dynamic content, or do I need to rely on JavaScript

Imagine a scenario where I have a single-page website and I want to optimize the loading time by only displaying content below the fold when the user clicks on a link to access it. However, I don't want users with disabled JavaScript to miss out on th ...

The SDK generated by AWS API Gateway does not include the JavaScript client file

After setting up my API with the AWS Api Gateway Service, I am now looking to integrate the javascript SDK into a basic webpage. The provided instructions for using the javascript SDK can be found here. However, they mention importing a js file named apig ...

Even though I am aware that the variable AJAX is attempting to return is not empty, it is still returning 'undefined'

I wrote a basic PHP script that retrieves information from a database and stores it in a multidimensional array: <?php //PHP code to fetch data from DB error_reporting(E_ALL); $db = new mysqli("localhost","root","pass", "Media") ...

The GM_xmlHttpRequest POST method is not functioning properly when called within an event listener

My simple goal is to intercept xmlHttpRequests sent by a page and send them to my local server for logging in a text file. However, Ajax calls do not work in event listeners. I have tried various solutions all day long without success. Here is the code sni ...

Is it possible to input rendered HTML into a vue property?

I am currently utilizing vue-material and running into the following situation: <md-dialog-confirm :md-active="true" md-title="Make an Outbound Call" md-confirm-text="Agree" md-cancel-text="Disagree" md-content="some <p>HTML ...

Utilizing Redux with React class components: A comprehensive guide

I have been attempting to integrate Redux with React Class using TypeScript, following the guidelines provided in this tutorial. However, I am encountering numerous compilation errors and feeling overwhelmed as to where to begin troubleshooting. It is cl ...

Utilizing next-redux-wrapper within the getServerSideProps function in Next.js allows for seamless

When trying to call an action function in getServerSideProps using TypeScript, I encountered some challenges. In JavaScript, it is straightforward: import { wrapper } from "Redux/store"; import { getVideo } from "Redux/Actions/videoAction&qu ...

Developing an npm package for storing a communal instance

I am interested in developing an npm library that can be initialized with a specific set of keys and then utilized throughout an entire project. Here is an illustration of how I envision its usage: In the main component or page import customLib from &quo ...

Creating an object with an array of objects as a field in MongoDB: A step-by-step guide

I have a unique schema here: const UniqueExerciseSchema = new Schema({ exerciseTitle: { type: String }, logSet: [{ weight: { type: Number }, sets: { type: Number }, reps: { type: Number }, }], }); After obtaining the da ...

Successfully resolved: Inability to dynamically adjust button color according to its state

Currently I am working on a feature where a button changes color when it is disabled, but also has a custom color when enabled. Here is the code snippet I am using: Despite setting blue text for the button, it remains blue even after becoming disabled. Ho ...

Using Typescript with d3 Library in Power BI

Creating d3.axis() or any other d3 object in typescript for a Power BI custom visual and ensuring it displays on the screen - how can this be achieved? ...

What is the method to extract mimeType from an HTMLImageElement?

After researching the MDN documentation on HTMLImageElement, I found no mention of the mimeType. I did come across some resources explaining how to retrieve the mimeType from a File Object. However, my specific requirement is to extract the mimeType from ...

Leveraging JavaScript code repeatedly

Apologies if this question has been asked before, as I couldn't find it. I have an HTML table with images used as buttons: <td> <button class="trigger"> <img src="D:\Elly Research\ CO2858\Presentation\Calypso ...

Encountering an ETIMEDOUT error while sending out large (10k) post requests with axios.all in a Node

I have implemented axios.all to make simultaneous post calls. Below is the code snippet: let postUrls = []; data.forEach(item => { const itemData = { stream: stream_name, key: item.serialNumber, addr ...

What is the best way to display the outcome in a popup window?

I am looking to display the result in a pop-up window. Code: <?php $con=mysqli_connect("localhost","root","1234","fyp"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $result = ...

The sort function in Reactjs does not trigger a re-render of the cards

After fetching data from a random profile API, I am trying to implement a feature where I can sort my profile cards by either age or last name with just a click of a button. Although I managed to get a sorted array displayed in the console log using the h ...

What causes the app to crash in release mode when importing a TypeScript component, while no issues arise in debugging?

Having an issue with importing a bottom sheet written in typescript into a class component. It works correctly in debugging mode but unfortunately not in release mode. Despite checking the logcat, no readable error code or message is being printed. Even a ...