Search code examples
javaxmlvalidationxsdxstream

Value is not facet-valid with respect to pattern


I have this element in a XSD:

<xs:simpleType name="elementWithAsterisks">
  <xs:restriction base="xs:string">
    <xs:length value="16"/>
    <xs:pattern value="^[0-9*]*$"/>
  </xs:restriction>
</xs:simpleType>

The value of this element can be a number, or a number and asterisk, and its length must be 16 characters. For example, the following strings should be valid:

 **1234567****01456**
 **1234567890654321**
 1***************

If I send a value like that to this element, XStream returns this message:

cvc-pattern-valid: Value '1234567****01456' is not facet-valid with respect to pattern '^[0-9*]*$' for type 'elementWithAsterisks'.

I'm using Java with XStream. This is my code to validate it:

try {
    File xsdFile = new File("validation.xsd");
    SchemaFactory schemaFactory = SchemaFactory.newInstance(SCHEMA_LANGUAGE);
    factory.setSchema(schemaFactory.newSchema(xsdFile);
    SAXParser saxParser = factory.newSAXParser();
    XMLReader reader = saxParser.getXMLReader();
    reader.setErrorHandler(new XmlValidationErrorHandler());
    reader.parse(new InputSource(inputStream));
    isValid = true;
} catch (SAXException | ParserConfigurationException | IOException ex) {
    ex.printStackTrace();
    isValid = false;
}

Solution

  • Regular expressions in XSD are implicitly surrounded by ^ and $. Simply remove the explicit (redundant) ones from your xs:pattern, and your XSD will work as expected:

      <xs:pattern value="[0-9*]*"/>