Jax ws-xs:日期格式验证 [英] Jax ws- xs:date format validation

查看:196
本文介绍了Jax ws-xs:日期格式验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在XSD中有这个(请检查下面的代码):

I have this in my XSD (please check code below):

<xs:element name="Report_Date" type="xs:date" minOccurs="0"/>

这个字段确实只接受日期格式yyyy-mm-dd以及是否有其他格式给出了,JAXB将其解组为null。

it is true that this field accepts only the date format yyyy-mm-dd and if any other format is given, JAXB unmarshalls it as null.

但我想验证report_date字段中的请求中给出的格式是否错误。
由于这是一个可选字段,即使未给出日期和日期格式不正确,应用程序的行为也相同。

But i want to validate the report_date field for incorrect format given in the request. Since this is an optional field, the application behaves same for even when the date not given and when the date is given in incorrect format.

为简单起见,如果指定的格式不正确,我想从应用程序中抛出错误消息。 XMLAdapter无法提供帮助,因为即使它被解组为null。

To make it simple, i want to throw error message from application if incorrect format is specified. XMLAdapter couldnt help,as even there it is unmarshalled as null.

此外,我没有选择在xsd中将xs:date的类型更改为字符串。

Also i dont have a choice to change the type of xs:date to string in xsd.

推荐答案

xs:date 接受的格式多于 YYYY -MM-DD (参见此处)。

xs:date accepts more formats than just YYYY-MM-DD (see here).

下面的代码实现了上述指导原则。

Below code implements above guidelines.

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();
}

这篇关于Jax ws-xs:日期格式验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆