How to check mandatory field whether it is empty or not in Selenium WebDriver using Java?
Solution 1
Way 1: First, write the following method:
private boolean isTextPresent(String text){
try{
boolean b = driver.getPageSource().contains(text);
return b;
}
catch(Exception e){
return false;
}
}
Now do assertion whether the expected message is present or not on the page by calling the above method:
assertTrue(isTextPresent("Value is required and can't be empty"), "Msg is absent/wrong/misspelled");
Way 2: Another way is as follow:
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
private StringBuffer verificationErrors = new StringBuffer();
try {
assertTrue(driver.findElement(By.cssSelector("BODY")).getText().matches("^[\\s\\S]*Value is required and can't be empty[\\s\\S]*$"));
} catch (Error e) {
verificationErrors.append(e.toString());
}
}
Solution 2
You can use assert
for checking the mandatory field alert is appearing or not, with try-catch
try {
assertEquals("Value is required and can't be empty", driver.findElement(By.xpath("XPATH_OF_LABLE")).getText());
} catch (Error e) {
//code for the case when the texts are not same
verificationErrors.append(e.toString());
}
the example is using xpath, but you can use any other locator method for this.
Solution 3
Use SoftAssert
to validate all of the mandatory fields in a form by a single @Test
annotation. Even if any of the assertions fail, it will execute the next line and gives us the all exception caught in @Test
when we do assertAll()
at the end.
driver.findElement(by.id("submit")).click();
SoftAssert softAssert = new SoftAssert();
softAssert.assertEquals(firstname.getText(), "First Name is required");
softAssert.assertEquals(lastname.getText(), "Last Name is required");
softAssert.assertEquals(email.getText(), "Email Address is required");
softAssert.assertAll();
Nasrin Naher
Updated on June 05, 2022Comments
-
Nasrin Naher almost 2 years
I am working on "add new user form" . In this form, there are several mandatory fields. Form will not be submitted when any mandatory field is empty and it will show a validation message like : "Value is required and can't be empty". How can I check/automate the form whether field is empty or not?
-
Ripon Al Wasim over 10 years2nd one is more preferable
-
Nasrin Naher over 10 yearsBut finally I used 2nd one.
-
Ripon Al Wasim over 10 years@NasrinNaher: Best of luck