Jax ws- xs:date format validation

2019-07-17 03:53发布

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条回答
祖国的老花朵
2楼-- · 2019-07-17 04:26

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();
}
查看更多
登录 后发表回答