Selenium Get, Capture & display the validation error message

Abhishek Dhoundiyal
2 min readFeb 26, 2023

--

In our day to day task we get into cases, where we need to verify the form validation message and had to verify the state of the element.

Let’s take an example to understand it better.

Check the below screenshot and let’s assume we want to get the validation error message which is displayed in the screenshot attached.

Yes, you can easily get the validation message and the state by using the JavascriptExecutor in selenium. Which basically help us in Selenium to execute Javascript code.

But First we have to understand the two important things:

  1. The checkValidity() method checks whether the element has any constraints and whether it satisfies them. If the element fails its constraints, the browser fires a cancelable invalid event at the element, and then returns false.
  2. The validationMessage read-only property that returns the validation message for the element.

Code:

WebElement ele = driver.findElement(By.id(""));
JavascriptExecutor js = (JavascriptExecutor) driver;
Boolean isValidInput = (Boolean)js.executeScript("return arguments[0].checkValidity();", ele);
System.out.println(isValidInput);
String validationMessage = (String)js.executeScript("return arguments[0].validationMessage;", ele);
System.out.println(validationMessage);

Output:

Note: You just need to provide the input WebElement for each input tag.

References:

--

--

No responses yet