[html] Limit number of characters allowed in form input text field

How do I limit or restrict the user to only enter a maximum of five characters in the textbox?

Below is the input field as part of my form:

<input type="text" id="sessionNo" name="sessionNum" />

Is it using something like maxSize or something like that?

This question is related to html forms input textbox

The answer is


The maximum number of characters that will be accepted as input. This can be greater that specified by SIZE , in which case the field will scroll appropriately. The default is unlimited.

<input type="text" maxlength="2" id="sessionNo" name="sessionNum" onkeypress="return isNumberKey(event)" />

However, this may or may not be affected by your handler. You may need to use or add another handler function to test for length, as well.

The simplest way to do so:


So.. Adding this attribute to your control:

<input type="text" 
    onkeypress="return isNumberKey(event)" 
    maxlength="5" />

According to w3c, the default value for the MAXLENGTH attribute is an unlimited number. So if you don't specify the max a user could cut and paste the bible a couple of times and stick it in your form.

Even if you do specify the MAXLENGTH to a reasonable number make sure you double check the length of the submitted data on the server before processing (using something like php or asp) as it's quite easy to get around the basic MAXLENGTH restriction anyway

Add the following to the header:

<script language="javascript" type="text/javascript">
function limitText(limitField, limitNum) {
    if (limitField.value.length > limitNum) {
        limitField.value = limitField.value.substring(0, limitNum);

    <input type="text" id="sessionNo" name="sessionNum" onKeyDown="limitText(this,5);" 
onKeyUp="limitText(this,5);"" />

Make it simpler

<input type="text" maxlength="3" />

and use an alert to show that max chars have been used.

<input type="text" maxlength="5">

the maximum amount of letters that can be in the input is 5.

I alway do it like this:

var maxChars = $("#sessionNum");
var max_length = maxChars.attr('maxlength');
if (max_length > 0) {
    maxChars.on('keyup', function(e){
        length = new Number(maxChars.val().length);
        counter = max_length-length;


<input name="sessionNum" id="sessionNum" maxlength="5" type="text">
Number of chars: <span id="sessionNum_counter">5</span>


The maximum number of characters that will be accepted as input. The maxlength attribute specifies the maximum number of characters allowed in the element.

Maxlength W3 schools

<form action="/action_page.php">
    Username: <input type="text" name="usrname" maxlength="5"><br>
    <input type="submit" value="Submit">

You can use <input type = "text" maxlength="9"> or

<input type = "number" maxlength="9"> for numbers or <input type = "email" maxlength="9"> for email validation will show up

The following code includes a counted...

var count = 1;_x000D_
do {_x000D_
    function count_down(obj, count){_x000D_
    let element = document.getElementById('count'+ count);_x000D_
    element.innerHTML = 80 - obj.value.length;_x000D_
    if(80 - obj.value.length < 5){_x000D_
        element.style.color = "firebrick";_x000D_
        element.style.color = "#333";_x000D_
} while (count < 20); 
.text-input {_x000D_
    padding: 8px 16px;_x000D_
    width: 50%;_x000D_
    margin-bottom: 5px;_x000D_
    margin-top: 10px;_x000D_
    font-size: 20px;_x000D_
    font-weight: 700;_x000D_
    font-family: Raleway;_x000D_
    border: 1px solid dodgerblue;_x000D_
<p><input placeholder="Title" id="bike-input-title" onkeyup="count_down(this, 3)" maxlength="80"  class="text-input" name="bikeTitle" ></p>_x000D_
        <span id="count3" style="float: right; font-family: Raleway; font-size:20px; font-weight:600; margin-top:-5px;">80</span><br>

<input type="number" id="xxx" name="xxx" oninput="maxLengthCheck(this)" maxlength="10">

function maxLengthCheck(object) {
  if (object.value.length > object.maxLength)
  object.value = object.value.slice(0, object.maxLength)

Use maxlenght="number of charcters"

<input type="text" id="sessionNo" name="sessionNum" maxlenght="7" />

<input type="text" name="MobileNumber" id="MobileNumber" maxlength="10" onkeypress="checkNumber(event);"  placeholder="MobileNumber">

function checkNumber(key) {
  var inputNumber = document.querySelector("#MobileNumber").value;
  if(key.key >= 0 && key.key <= 9) {
    inputNumber += key.key;
  else {

Questions with html tag:

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment Angular 6: saving data to local storage Vue.js get selected option on @change Bootstrap 4 multiselect dropdown How to add bootstrap in angular 6 project? Angular 5 Button Submit On Enter Key Press Angular 5, HTML, boolean on checkbox is checked How to render string with html tags in Angular 4+? bootstrap 4 file input doesn't show the file name How can I execute a python script from an html button? Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width Failed to load resource: the server responded with a status of 404 (Not Found) css Change arrow colors in Bootstraps carousel Bootstrap 4 Dropdown Menu not working? CSS Grid Layout not working in IE11 even with prefixes How to prevent page from reloading after form submit - JQuery Centering in CSS Grid Detecting real time window size changes in Angular 4 Angular 4 img src is not found (change) vs (ngModelChange) in angular Bootstrap 4: Multilevel Dropdown Inside Navigation Align the form to the center in Bootstrap 4 How to style a clicked button in CSS How do I change the font color in an html table? Redirecting to a page after submitting form in HTML Load json from local file with http.get() in angular 2 display: flex not working on Internet Explorer Scroll to element on click in Angular 4 How to extract svg as file from web page force css grid container to fill full screen of device How does the "position: sticky;" property work? HTML5 Video autoplay on iPhone Disable button in angular with two conditions? CSS hide scroll bar, but have element scrollable CSS grid wrapping How to load image (and other assets) in Angular an project? Flask - Calling python function on button OnClick event How can I make Bootstrap 4 columns all the same height? Wrapping a react-router Link in an html button

Questions with forms tag:

How do I hide the PHP explode delimiter from submitted form results? React - clearing an input value after form submit How to prevent page from reloading after form submit - JQuery Input type number "only numeric value" validation Redirecting to a page after submitting form in HTML Clearing input in vuejs form Cleanest way to reset forms Reactjs - Form input validation No value accessor for form control TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm" Angular 2: Can't bind to 'ngModel' since it isn't a known property of 'input' In Angular, how to add Validator to FormControl after control is created? How to disable input conditionally in vue.js Mask for an Input to allow phone numbers? angular2 submit form by pressing enter without submit button How to convert Base64 String to javascript file object like as from file input form? Manually Set Value for FormBuilder Control Angular 2: Get Values of Multiple Checked Checkboxes Can I use an HTML input type "date" to collect only a year? How to make 'submit' button disabled? Angular2 - Radio Button Binding How to redirect back to form with input - Laravel 5 Adding form action in html in laravel Multiple radio button groups in one form Setting onSubmit in React.js Laravel form html with PUT method for PUT routes How To Pass GET Parameters To Laravel From With GET Method ? Show loading gif after clicking form submit using jQuery Postman Chrome: What is the difference between form-data, x-www-form-urlencoded and raw How to submit an HTML form without redirection Laravel - Form Input - Multiple select for a one to many relationship Angularjs how to upload multipart form data and a file? How to hide form code from view code/inspect element browser? jQuery AJAX form data serialize using PHP How to make <label> and <input> appear on the same line on an HTML form? Form Submission without page refresh Fetching data from MySQL database using PHP, Displaying it in a form for editing Adding asterisk to required fields in Bootstrap 3 What's the difference between "Request Payload" vs "Form Data" as seen in Chrome dev tools Network tab How to get HTML 5 input type="date" working in Firefox and/or IE 10 Laravel use same form for create and edit Send value of submit button when form gets posted Angular is automatically adding 'ng-invalid' class on 'required' fields Submit form after calling e.preventDefault() How to send a JSON object using html form data Comparing two input values in a form validation with AngularJS Jquery function BEFORE form submission Clear text input on click with AngularJS Access Form - Syntax error (missing operator) in query expression How to Call a JS function using OnClick event

Questions with input tag:

Angular 4 - get input value React - clearing an input value after form submit Min and max value of input in angular4 application Disable Button in Angular 2 Angular2 - Input Field To Accept Only Numbers How to validate white spaces/empty spaces? [Angular 2] Can't bind to 'ngModel' since it isn't a known property of 'input' Mask for an Input to allow phone numbers? File upload from <input type="file"> Why does the html input with type "number" allow the letter 'e' to be entered in the field? HTML Input - already filled in text How to get multiline input from user Get input value from TextField in iOS alert in Swift HTML Input Type Date, Open Calendar by default Reading an integer from user input Why cannot change checkbox color whatever I do? How to properly validate input values with React.JS? How do I make an input field accept only letters in javaScript? How to read multiple Integer values from a single line of input in Java? Hide Spinner in Input Number - Firefox 29 How to take character input in java How to input matrix (2D list) in Python? Input type "number" won't resize Want to show/hide div based on dropdown box selection input() error - NameError: name '...' is not defined Get the value of input text when enter key pressed Play audio as microphone input How can I read inputs as numbers? How to force input to only allow Alpha Letters? Multiple input box excel VBA How can I get input radio elements to horizontally align? Is there a float input type in HTML5? how to customise input field width in bootstrap 3 Change input value onclick button - pure javascript or jQuery onchange event on input type=range is not triggering in firefox while dragging html form - make inputs appear on the same line What does "for" attribute do in HTML <label> tag? How to style HTML5 range input to have different color before and after slider? Java using scanner enter key pressed Styling input radio with css Check if input is number or letter javascript How do I check if the user is pressing a key? How to make a input field readonly with JavaScript? Detect key input in Python Image convert to Base64 How to change the text color of first select option Getting Keyboard Input jQuery 'input' event How to make <input type="file"/> accept only these types? HTML how to clear input using javascript?

Questions with textbox tag:

Add two numbers and display result in textbox with Javascript How to check if a text field is empty or not in swift Setting cursor at the end of any text of a textbox Press enter in textbox to and execute button command javascript getting my textbox to display a variable How can I set focus on an element in an HTML form using JavaScript? jQuery textbox change event doesn't fire until textbox loses focus? PHP: get the value of TEXTBOX then pass it to a VARIABLE How to clear a textbox once a button is clicked in WPF? Get current cursor position in a textbox Make TextBox uneditable How to capture Enter key press? Adding new line of data to TextBox How to trigger HTML button when you press Enter in textbox? Only allow specific characters in textbox Validating a Textbox field for only numeric input. Open file dialog and select a file using WPF controls and C# VB.net Need Text Box to Only Accept Numbers Change the borderColor of the TextBox Add values from two textboxes and display the sum in third textbox Getting input values from text box Limit number of characters allowed in form input text field How to add a line to a multiline TextBox? How to disable textbox from editing? How to make a TextBox accept only alphabetic characters? How can I add a hint text to WPF textbox? What is the correct value for the disabled attribute? Add padding to HTML text input field html text input onchange event Check if TextBox is empty and return MessageBox? Setting maxlength of textbox with JavaScript or jQuery Multiline TextBox multiple newline VBA Excel Provide current Date in Text box Change the Textbox height? changing textbox border colour using javascript C# Numeric Only TextBox Control How to set alignment center in TextBox in ASP.NET? How to clear the text of all textBoxes in the form? HTML/CSS Making a textbox with text that is grayed out, and disappears when I click to enter info, how? Passing javascript variable to html textbox Which passwordchar shows a black dot (•) in a winforms textbox? Best way to restrict a text field to numbers only? VB.Net .Clear() or txtbox.Text = "" textbox clear methods Enter key pressed event handler Getting the .Text value from a TextBox How do I set a textbox's text to bold at run time? Disable button in WPF? How to change the font color in the textbox in C#? Multiline for WPF TextBox Disable a textbox using CSS