selenium date validation

Solved 1 Answers 172 Views Programming
0 1
Is there anyway we can check for date validity when inputting dates? For example if you are trying to input a date that has already passed the system should stop you

1 Answer

Best answer
Step 1: Get the text from an element

WebElement element = driver.findElement([Idenitfy your element here]);

Once you get the element. Get content of the element

String sDate = element.getText();

if you are getting date value from Textbox, try

String sDate = element.getAttribute("value");

Step 2: Convert string to Date. e.g. Your date is  February 3, 2015

DateFormat format = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);
Date date = format.parse(sDate);

Step 3: Get today's date
Calendar c = new GregorianCalendar();
c.set(Calendar.HOUR_OF_DAY, 0); //anything 0 - 23
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
Date today = c.getTime();

Step 4: compare two dates
boolean sameDay = date.get(Calendar.YEAR) == today.get(Calendar.YEAR) &&
                  date.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR);
answered by (327 points)
selected by

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.

We have resolved 1.2k+ Software Testing queries!

Top Contributors