john.p.doe
john.p.doe

Reputation: 521

Not able to validate Date against XSD

I am trying to implement basic validation on XML against a defined XSD XML:

<Employee type="permanent">
    <Name>John</Name>
    <employeeId>9000</employeeId>
    <Age>28</Age>
    <dateOfBirth>28/12/2000</dateOfBirth>
    <city>Vancouver</city>
    <salary>120000</salary>
</Employee>

XSD:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="Employee">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="Name" type="xs:string"></xs:element>
                <xs:element name="employeeId" type="xs:int"></xs:element>
                <xs:element name="Age" type="xs:int"></xs:element>
                <xs:element name="dateOfBirth" type="xs:date"></xs:element>
                <xs:element name="city" type="xs:string"></xs:element>
                <xs:element name="salary" type="xs:int"></xs:element>
            </xs:sequence>
            <xs:attribute name="type" type="xs:string"></xs:attribute>
        </xs:complexType>
    </xs:element>
</xs:schema>

But when I run the validator:

SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = factory.newSchema(new File(schemaPath));
            Validator validator = schema.newValidator();
            validator.setErrorHandler(new BasicErrorHandler());
            validator.validate(new StreamSource(new File(xmlPath)));

I keep getting the following error:

cvc-datatype-valid.1.2.1: '12/28/2000' is not a valid value for 'date'.
cvc-type.3.1.3: The value '12/28/2000' of element 'dateOfBirth' is not valid.

Now when I tried searching for a solution on SO and Google here is what I found:

<xs:element name="root">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="testdate" type="zsdate"/>
                <xs:element name="testtime" type="zstime"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>

    <xs:simpleType name="zsdate">
        <xs:restriction base="xs:date">
            <xs:pattern value="^(0[1-9]|[12][0-9]|3[01]).(0[1-9]|1[012]).(19|20)\d\d$"/>
        </xs:restriction>
    </xs:simpleType>

I do not want to convert the data type to string and validate against a regex. My date will always be in dd/mm/yyyy format. The way it is written in XML pasted above.

Is there something that I am missing.

P.S. when I use the following:

   <dateOfBirth>2012-08-22</dateOfBirth>

it works fine.

Upvotes: 0

Views: 1199

Answers (1)

halloei
halloei

Reputation: 2046

<xs:date> must be in YYYY-MM-DD format. So either you write it that way or you take <xs:string> with the regex.

Upvotes: 2

Related Questions