Is there a way to restrict my input to only 10 numbers without allowing any characters?

Is there a way to restrict the phone number input to only allow 10 numbers and exclude any other characters? Currently, setting the maxLength attribute limits the characters to 10 but allows additional characters as well.

If I change the type attribute to type="number", maxLength no longer functions properly and certain characters like [minus(-) or plus(+)] are still accepted.

What steps can be taken to ensure that the input field only accepts a maximum of 10 numbers and disallows any other characters?

<input
  placeholder="Telephone Number"
  className="input_fields telephone_no"
  type="tel"
  maxLength={"10"}
  name="phoneNumber"
  id="teacher_telephone_no"
  value={this.state.user.phoneNumber}
  onChange={e =>
    this.setState({
      user: {
        ...this.state.user,
        [e.target.name]: e.target.value
      }
    })
  }
/>

Answer №1

To ensure that the input is valid before updating the state, you can utilize regular expressions (regex) like so:

     <input
        placeholder="Enter your email"
        className="input_field email_input"
        type="email"
        maxLength={"50"}
        name="userEmail"
        id="email_address"
        value={email}
        onChange={(e) => {
          if (/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(e.target.value)) {
             this.setState({
               email: {
               ...this.state.email,
               [e.target.name]: e.target.value
               }
            })
          }
        }}
      />

Answer №2

To prevent users from typing symbols, you can utilize regular expressions and the keyup event.

let input = document.querySelector('input')
input.onkeyup = function() {
  input.value = input.value.replace(/[^\d]/, "")

}
<input placeholder="Telephone Number" className="input_fields telephone_no" type="tel" maxLength={ "10"} name="phoneNumber" id="teacher_telephone_no" />

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

Can you explain the concept of a TransientTransactionError within Mongoose (or MongoDB)?

Two important files in my project are server.js and db.js. The db.js file is responsible for interacting with the database using Mongoose, while server.js calls functions from db.js: var mongoose = require('mongoose'); mongoose.connect('&ap ...

What could be the reason for Jest's failure to execute tests involving npm packages?

I recently started a new project using the create-react-library package. In an attempt to add unit tests with Jest and Enzyme, I encountered an issue. While my test functions properly for a basic component, it fails when trying to test a component that inc ...

Is there a way to simulate the parameters injected into an fs callback without actually interacting with the filesystem during testing?

I'm currently utilizing Chai, Mocha, and Sinon for my testing framework. At the moment, I have a functioning test, but I find myself having to set up a directory and populate it with files just to make my tests run successfully. This approach doesn&a ...

Waiting for update completion in Firebase Firestore (Javascript for web development)

When I retrieve a document, update it, and then try to access the updated data, I am getting undefined logged. Can anyone explain why this is happening and suggest a solution for successfully fetching the new data from the document? db.collection("collect ...

Unraveling complex JSON structures in Node.js

I've been working on parsing nested JSON data and here is the code I'm currently using var str = '{"key1": "value", "key2": "value1", "Key3": {"key31":"value 31"}}'; v ...

Discovering the final pattern using regular expressions

var inputString = 'a.b.c.d.e.f'; var pattern = inputString.match(/([^\.]+)\.[^\.]+$/)[1]; console.log(pattern); I have successfully implemented the code using regular expressions, but I am open to exploring more efficient solution ...

Retrieving posts from a Facebook page by utilizing the FB API

Throughout the previous summer, I managed a website (not my own) that pulled in posts from its corresponding Facebook page and displayed them on a designated page. I utilized an application token for this process, but now it no longer functions due to the ...

Understanding the Variable Scope in Event Listeners and Asynchronous AJAX Functions

Here's a question that might seem simple to some, but I'm not sure. So, when you register an event listener within an asynchronous function, one would think that all values within that function would be inaccessible once the function has complete ...

cannot wait for promise in loop to avoid delaying the request

In the API endpoint of a Next.js webapp, this code is designed to fetch all the GitHub repositories, including their names and number of contributors. However, an issue arises when using Promise.all - the call does not return anything (resulting in a stall ...

Explanation requested for previous response about returning ajax data to the parent function

After coming across a helpful answer in the question titled How do I return the response from an asynchronous call?, I attempted to implement it without success. Reviewing Hemant Bavle's answer (currently with 62 votes) gave me hope, but my implement ...

Authentication for file uploads in Angular 2 using Dropzone and passportjs

I am currently working on implementing authentication for an admin user using Express, Passport, and MySQL in a specific page. The authentication process works fine, but I am facing an issue with verifying whether the user is logged in while uploading file ...

How to set the value of an `<input type="date"` in jQuery

Having trouble figuring out why this code isn't functioning properly. The input field I'm using is a simple 'input type="date"' setup like this.... <input type="date" name="Date"/> I am attempting to have the value automatically ...

Modify the background color of React-select when it is in a disabled state

I found this interesting tip on color customization in React Select When the select field is disabled, I want to change its color to something different. isDisabled={true} To achieve this, I am modifying the code as follows: > import React from &q ...

How to selectively filter an array of objects using another array in JavaScript

Imagine you have an array filled with objects: people = [ {id: "1", name: "abc", gender: "m", age:"15" }, {id: "2", name: "a", gender: "m", age:"25" }, {id: "3 ...

What methods can be used to restrict user input to numbers and letters only?

Is it possible to restrict the input in my text field username without using regex? I want users to only enter numbers and letters, with no white spaces or special characters. <div class="form-group has-feedback" ng-class="addUser.username.$valid ? &ap ...

Building a custom onChange event handler in Formik allows for greater

I want to modify the onChange function in formik input so that it converts the value from a string to a number. However, I'm unable to change the behavior as expected and the console.log doesn't show up on the screen. It seems like Formik's ...

Smooth-scroll plugin does not activate active state (due to JS modification)

I'm currently facing an issue with a script that handles smooth scrolling and the active state on my main navigation. The plugin in question can be found at: It's important to note that the navigation bar is fixed and therefore has no height. T ...

Efficiently process 100 tasks per minute using a microservice architecture

I have a node.js application that needs to perform the following tasks: Retrieve zip files, extract them (containing JS module files with key-value pairs - usually 5-8 files per request) Analyze these files, create new ones from the analysis, and ...

Modify the hover color of <TextField /> within the createMuiTheme() function

Is there a way to change the borderColor on hover for the outlined <TextField /> Component within the createMuiTheme()? I have managed to do it easily for the underlined <Input /> export default createMuiTheme({ MuiInput: { &apo ...

The MongoDB regex is failing to provide the expected outcome

I'm facing an issue with searching data in MongoDB. I have a table with approximately 5000 entries of data that need to be searched based on multiple columns with specific priority criteria. The first priorities for the search are symbol, name, co_nam ...