How to set a character limit on an Input field in React.js

The main content of this article will be about how to set a character limit on an input field in React.js. Some ways can be mentioned, such as using the maxLength attribute or the condition with input length.

Set a character limit on an Input field

Using the maxLength attribute

The HTML <input> or input tag in HTML represents an input field where you can enter data. Input tag is supported with many attributes to help developers quickly change the tag’s attributes. In this example, we will use its maxLength attribute. Please take a look at the code below to understand how it works.

Code:

const App = () => {

    return (
        <div>
            <h2>Enter a message :</h2>
            <input
                type="text"
                maxLength={11}
            />
        </div>
    );
};

export default App;

Output:

When you set the input tag to the maxLength attribute, the input will only accept up to the number of characters you set it to. If we enter a value longer than the max length of the input, the value in the input remains the same. That’s how you set a character limit on an input field in React.js using the input’s built-in maxLength property, or you can also refer to other ways in the next part of the article.

Using the condition with input length

We can access the current input value by catching the onChange event and accessing the event.target.value. So every time the user changes the value inside the input, the handler function will be run, and we can check the length of the value in the current input.

Code:

const App = () => {

    const handleChange = (e) => {
        if (e.target.value.length > 11) {
            alert(" Message can NOT be longer than 11 characters");
            e.target.value = "";
        }
    }

    return (
        <div>
            <h2>Enter a message :</h2>
            <input
                type="text"
                onChange={handleChange}
            />
        </div>
    );
};

export default App;

Output:

With a simple, if conditional, we could set a character limit on an input field by comparing the value. length value with the limit length we need to set. When the user enters too long, the input will be reset to null, and an alert validation will appear. Wish you success with the two ways mentioned in the article

Summary

Summarizing the article, we have learned two ways to set a character limit on an input field in React.js. However, using the maxLength property is easier and more compact because it is already built in to do this.

Leave a Reply

Your email address will not be published. Required fields are marked *