How to get HTML5 validation message with selenium?

前端 未结 2 667
無奈伤痛
無奈伤痛 2021-02-10 15:18

Please see this website.

After click log in i have this User credentials form and after try to login with missing Email Address or Password i g

2条回答
  •  遇见更好的自我
    2021-02-10 15:32

    Attribute validationMessage will return the message, that will be showing if validation fails:

    WebElement username = driver.findElement(By.name("uname"));    
    String validationMessage = username.getAttribute("validationMessage");
    

    If element has required attribute, browser will show the message after submitting the form:

    boolean required = Boolean.parseBoolean(username.getAttribute("required"));
    

    You can check whether entered value is valid:

    boolean valid = (Boolean)((JavascriptExecutor)driver).executeScript("return arguments[0].validity.valid;", username);
    


    Not: message text and validation is customizable. If you want to test customized validation and message.

    Here test code for custom validation(Java, TestNG):

    Assert.assertTrue(Boolean.parseBoolean(username.getAttribute("required")), "Username is required and message should be showin");
    Assert.assertEquals(username.getAttribute("validationMessage"), "My custom message", "Message text control");
    
    username.sendKeys("@vasya ");
    Assert.assertTrue((Boolean)((JavascriptExecutor)driver).executeScript("return arguments[0].validity.valid;", username), "Username has special characters");
    

提交回复
热议问题