Hello!
I'm just wondering if there is a way (maybe with REGEX) to validate that an input on a java desktop app is exactly an string formated as: "YYYY-MM-DD".
I've search but with no success.
Thank you
Hello!
I'm just wondering if there is a way (maybe with REGEX) to validate that an input on a java desktop app is exactly an string formated as: "YYYY-MM-DD".
I've search but with no success.
Thank you
Use the following regular expression:
^\d{4}-\d{2}-\d{2}$
as in
if (str.matches("\\d{4}-\\d{2}-\\d{2}")) {
...
}
With the matches
method, the anchors ^
and $
(beginning and end of string, respectively) are present implicitly.
You want more than a regex, for example "9999-99-00" isn't a valid date. There's a SimpleDateFormat class that's built to do this. More heavyweight, but more comprehensive-
e.g.
SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-dd");
boolean isValidDate(string input)
{
try{ format.parse(input);return true;}
catch(ParseException e){ return false; }
}
Unfortunately, SimpleDateFormats are both heavyweight and not threadsafe.
Construct a SimpleDateFormat with the mask, and then call: SimpleDateFormat.parse(String s, ParsePosition p)
For fine control, consider an InputVerifier using the SimpleDateFormat("YYYY-MM-dd")
suggested by Steve B.
Putting it all together:
REGEX
doesn't validate values (like "2010-19-19") SimpleDateFormat
does not check format ("2010-1-2", "1-0002-003" are accepted) it's necessary to use both to validate format and value:
public static boolean isValid(String text) {
if (text == null || !text.matches("\\d{4}-[01]\\d-[0-3]\\d"))
return false;
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
df.setLenient(false);
try {
df.parse(text);
return true;
} catch (ParseException ex) {
return false;
}
}
private static final ThreadLocal<SimpleDateFormat> format = new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
df.setLenient(false);
System.out.println("created");
return df;
}
};
public static boolean isValid(String text) {
if (text == null || !text.matches("\\d{4}-[01]\\d-[0-3]\\d"))
return false;
try {
format.get().parse(text);
return true;
} catch (ParseException ex) {
return false;
}
}
(same can be done for a Matcher, that also is not thread safe)