Forum Discussion
ChrisAdams
2 years agoChampion Level 3
Hi,
There's loads of examples on the Internet about using Groovy to validate a string against a given date format. Lot's of regular expression examples and so on. I've done this elsewhere, but I use Date Parse inside a try-catch-finally block.
E.g. Here's Groovy snippet that shows how the date does not parse...
import static groovy.test.GroovyAssert.assertTrue;
def validated;
try {
validated = false;
def invalidDate = Date.parse('dd-MM-yyyy HH:mm:ss', '01\01\2001 09:02:58');
validated = true;
} catch(java.text.ParseException ex) {
log.info("Cannot Parse " + ex);
validated = false;
} finally {
log.info("Is my date string valid? " + validated);
//assertTrue("Is my date string valid? ", validated);
return validated;
}
And here's an example where it does parse and is therefore valid.
import static groovy.test.GroovyAssert.assertTrue;
def validated;
try {
validated = false;
def validDate = Date.parse('dd-MM-yyyy HH:mm:ss', '01-01-2001 09:02:58');
validated = true;
} catch(java.text.ParseException ex) {
log.info("Cannot Parse " + ex);
validated = false;
} finally {
log.info("Is my date string valid? " + validated);
//assertTrue("Is my date string valid? ", validated);
return validated;
}
This example works as a Groovy script. But if you dropped this into a script assertion, you can then use the commented out assertTrue as a real assertion.
Related Content
- 4 years ago
- 9 years ago
Recent Discussions
- 15 years ago