How To Verify Maximum Character Limit of an Input Box Through Selenium

Hello Folks,

Recently a guy asked me this question which he was asked in an interview in IBM.

What the ways to test maximum character limit of an input box through Selenium?

To achieve this in Selenium, we have two ways:

Suppose maximum character limit of an input box is 10 characters.

  1. Type more than 10 characters. It will get typed only first 10 characters and remaining will be ignored. Now get the typed value and assert its length to10.
  2. Get the attribute value of “maxlength” and assert it to10. “maxlength” is a property which is defined to set maximum allowed character limit for an input box.

Both ways are correct and can be used whatever you feel easy.

Html Code:

FirstName : <input type="text" name="username" maxlength="10">

Java Code:

package HandlingDropdown;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

public class VerifyMaxCharLimit {

	public static void main(String[] args) throws InterruptedException {

		System.setProperty("", "./exefiles/chromedriver.exe");
		WebDriver driver = new ChromeDriver();

		// Locating firstname web element
		WebElement firstNameInputbox = driver.findElement("username"));

		/***************** Way 1 ********************************/

		// Type more than 10 characters as max limit is defined as 10 as per requirement

		// Get the typed value
		String typedValue = firstNameInputbox.getAttribute("value");

		// Get the length of typed value
		int size = typedValue.length();

		// Assert with expected
		if (size == 10) {
			System.out.println("Max character functionality is working fine.");

		else {
			System.out.println("No limit is set.");

		/************************ Way 2 ********************************************/

		// Clear already typed value.

		// Get maxlength attribute of input box
		String maxLengthDefined = firstNameInputbox.getAttribute("maxlength");

		if (maxLengthDefined == null) {
			System.out.println("No limit is set.");

		else {
			if (maxLengthDefined.equals("10")) {
				System.out.println("Max character limit is set as expected.");

		// Closing driver



Max character functionality is working fine.
Max character limit is set as expected.

If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.

3 thoughts on “How To Verify Maximum Character Limit of an Input Box Through Selenium

  1. Hi Amodh,

    This article is very nice and informative.
    I have got one doubt , what if the maximum length is undefined or not known but definitely there is some restrictions on the number of characters a user can enter into the text field.
    How do you achieve this scenario?

Leave a Reply

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