Jax ws- xs:date format validation

大城市里の小女人 提交于 2020-01-04 19:04:10

问题


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

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

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.

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.

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.

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


回答1:


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


来源:https://stackoverflow.com/questions/20397661/jax-ws-xsdate-format-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!