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.
- 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.
- 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:
[html]
FirstName : <input type="text" name="username" maxlength="10">
[/html]
Java Code:
package HandlingDropdown; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class VerifyMaxCharLimit { public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.chrome.driver", "./exefiles/chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("file:///C:/Users/amodm/Downloads/InputWithMinMax.html"); // Locating firstname web element WebElement firstNameInputbox = driver.findElement(By.name("username")); /***************** Way 1 ********************************/ // Type more than 10 characters as max limit is defined as 10 as per requirement firstNameInputbox.sendKeys("Makeseleniumeasy"); // 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. firstNameInputbox.clear(); ; // 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 driver.quit(); } }
Output:
[java]
Max character functionality is working fine.
Max character limit is set as expected.
[/java]
If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.
#ThanksForReading
#HappySelenium
Thank you. It was helpful
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?
Hello,
Developer will put the restrictions either setting max attribute or logic. Way 1 will work here.