【问题标题】:Jax ws- xs:date format validationJax ws- xs:date 格式验证
【发布时间】:2013-12-05 10:36:17
【问题描述】:
我的 XSD 中有这个(请检查下面的代码):
<xs:element name="Report_Date" type="xs:date" minOccurs="0"/>
确实,该字段仅接受日期格式 yyyy-mm-dd,如果给出任何其他格式,JAXB 会将其解组为 null。
但我想验证report_date 字段是否存在请求中给出的不正确格式。
由于这是一个可选字段,因此即使没有给出日期和给出的日期格式不正确,应用程序的行为也是相同的。
为了简单起见,如果指定了不正确的格式,我想从应用程序中抛出错误消息。 XMLAdapter 无能为力,因为即使在那里它也被解组为 null。
我也没有选择将 xs:date 的类型更改为 xsd 中的字符串。
【问题讨论】:
标签:
java
web-services
validation
jaxb
date-format
【解决方案1】:
xs:date 接受的格式不仅仅是YYYY-MM-DD(参见here)。
下面的代码实现了上面的准则。
private static String twoDigitRangeInclusive(int from, int to) {
if (to<from) throw new IllegalArgumentException(String.format("!%d-%d!", from, to));
List<String> rv = new ArrayList<>();
for (int x = from; x <= to; x++) {
rv.add(String.format("%02d", x));
}
return StringUtils.join(rv, "|");
}
/**
* Checks whether the provided String is compliant with the xs:date datatype
* (i.e. the {http://www.w3.org/2001/XMLSchema}:date type)
* Known deviations: (1) years greater than 9999 are not accepted (2) year 0000 is accepted.
*/
public static boolean isXMLSchemaDate(String s) {
String regExp = String.format("-??\\d\\d\\d\\d-(%s)-(%s)(Z|((\\+|\\-)(%s):(%s)))??"
, twoDigitRangeInclusive(1, 12)
, twoDigitRangeInclusive(1, 31)
, twoDigitRangeInclusive(0, 23)
, twoDigitRangeInclusive(0, 59));
Pattern p = Pattern.compile(regExp);
return p.matcher(s).matches();
}