Home > OS >  How to extract the error hint of text box when user entered incorrect value in Selenium
How to extract the error hint of text box when user entered incorrect value in Selenium

Time:03-27

When incorrect value is entered in textbox next hint is appeared:

enter image description here

HTML:

<form action="/login" method="post" > <input type="hidden"> 
    <div > 
        <input type="email" name="_username" id="inputEmail" required="" autofocus="" autocomplete="off"> 
        <label for="inputEmail" >Email address</label> 
    </div> 
    <div > 
        <input type="password" name="_password" id="inputPassword" placeholder="Password" required=""> 
        <label  for="inputPassword">Password</label> 
    </div> 
</form>

I need to get text from this hint.

I have tried to used:

Alert alert = driver.switchTo().alert()->getText();

but it did not help.

How to get text from such hints?

CodePudding user response:

This error hint is basically the HTML5 Constraint validation message which is the outcome of Constraint API's element.setCustomValidity() method.

To get text from the error hint you need to induce WebDriverWait for the elementToBeClickable() and you can use either of the following locator strategies:

  • Using cssSelector:

    System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("input#inputEmail[name='_username']"))).getAttribute("validationMessage"));
    
  • Using xpath:

    System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@id='inputEmail' and @name='_username']"))).getAttribute("validationMessage"));
    

References

You can find a couple of relevant detailed discussions in:

  • Related