我的 XSD 中有这个(请检查下面的代码):
<xs:element name="Report_Date" type="xs:date" minOccurs="0"/>
该字段确实只接受日期格式 yyyy-mm-dd,如果给出任何其他格式,JAXB 会将其解码为 null。
但我想验证请求中给出的格式不正确的 report_date 字段。 由于这是一个可选字段,即使未提供日期和日期格式不正确,应用程序的行为也是相同的。
为简单起见,如果指定的格式不正确,我想从应用程序中抛出错误消息。 XMLAdapter 帮不上忙,因为即使在那里它也被解码为 null。
此外,我没有选择将 xs:date 的类型更改为 xsd 中的字符串。
最佳答案
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();
}
关于java - Jax ws- xs :date format validation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20397661/