How to test HTML5 validation messages with Selenium

HOME

<label for="email">Enter your example.com email:</label>

<input type="email" id="email" pattern=".+@example\.com" size="30" required />

ChromeOptions options = new ChromeOptions();
WebDriver driver = new ChromeDriver(options);
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
String filePath = "file:///C:/Users/vibha/OneDrive/Desktop/Email.html";
driver.get(filePath);

driver.manage().window().maximize();

WebElement email = driver.findElement(By.id("email"));
email.sendKeys("");
String validationMessage = email.getAttribute("validationMessage");
 String expectedMessage = "Please fill out this field.";
    if (validationMessage.equals(expectedMessage)) {
        System.out.println("Validation test passed. :" + validationMessage);
    } else {
        System.out.println("Validation test failed. Expected: '" + expectedMessage + "' but got: '" + validationMessage + "'");
    }

driver.quit();
package com.example.Sample;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.time.Duration;
import java.util.List;

public class HTML5Validation {

    public static void main(String[] args)  {

        // Setup the webdriver
        ChromeOptions options = new ChromeOptions();
        WebDriver driver = new ChromeDriver(options);

        // Put an Implicit wait and launch URL
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
        String filePath = "file:///C:/Users/vibha/OneDrive/Desktop/Email.html";
        driver.get(filePath);

        //maximize browser
        driver.manage().window().maximize();

        //Blank field
        WebElement email = driver.findElement(By.id("email"));
        email.sendKeys("");
        String validationMessage = email.getAttribute("validationMessage");

        // Expected validation message 
        String expectedMessage = "Please fill out this field.";
        if (validationMessage.equals(expectedMessage)) {
            System.out.println("Validation test passed. :" + validationMessage);
        } else {
            System.out.println("Validation test failed. Expected: '" + expectedMessage + "' but got: '" + validationMessage + "'");
        }

         // Close the browser
         driver.quit();
    }

}

Leave a comment