Many of you would have come across situation where you need to access required input field validation message and verify the message in your test
username field is defined as required seen in inspect of web page
When user submits the form without entering username, browser validation displays below message "Please fill out this field" under the input field
If you want to access this message string, one need to understand that message is displayed as part of browser validation for required input field and is not part of HTML code. Due to this, we can not access the element or message by defining xpath.
To access validation message, one need to understand, when user submitted the form, input field for which validation message is displayed is selected, in other words it became active element.
We can access active element using web driver switch to active element function call.
Now after we get active element reference, we can get pop up window validation message using validationMessage attribute for the element as below:
WebElement activeElement = driver.switchTo().activeElement();
String messageStr = activeElement.getAttribute("validationMessage");
System.out.println("Actual message appeared on screen: " + messageStr);
Here, messageStr will have value read from popup window as "Please fill out this field" which can be checked in your test case.