How can I extract the text of HTML5 Constraint validation in https://www.phptravels.net/ website using Selenium and Java? [duplicate]

The alert window in https://www.phptravels.net/ which you are referring is the outcome of Constraint API’s element.setCustomValidity() method.

Note: HTML5 Constraint validation doesn’t remove the need for validation on the server side. Even though far fewer invalid form requests are to be expected, invalid ones can still be sent by non-compliant browsers (for instance, browsers without HTML5 and without JavaScript) or by bad guys trying to trick your web application. Therefore, like with HTML4, you need to also validate input constraints on the server side, in a way that is consistent with what is done on the client side.

Solution

To retrieve the text which results out from the element.setCustomValidity() method, you can use the following solution:

  • Code Block:

    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.support.ui.ExpectedConditions;
    import org.openqa.selenium.support.ui.WebDriverWait;
    import org.openqa.selenium.By;
    
    public class HTML5_input_field_validation_message {
    
        public static void main(String[] args) {
    
            System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
            WebDriver driver = new FirefoxDriver();
            driver.get("https://www.phptravels.net/");
            WebElement checkin = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("input.form.input-lg.dpd1[name="checkin"]")));
            System.out.println(checkin.getAttribute("validationMessage"));
        }
    }
    
  • Console Output:

    Please fill out this field.
    

Leave a Comment