'Using Regex Pattern for Money with XML / XSD files
first time creating a schema - not sure what the issue is here.
I want to use a regex pattern that accepts an infinite number of digits to the left of a decimal point and only two digits to the right (standard dollar notation) as a custom data type for "price" as it is used in the XML document, however I'm receiving the following pair of errors:
"cvc-pattern-valid: Value '219.99' is not facet-valid with respect to pattern '^[0-9]+.[0-9]{2}$' for type 'money'."
"cvc-attribute.3: The value '219.99' of attribute 'price' on element 'product' is not valid with respect to its type, 'money'
Here's the relevant section from my XML file where "price" is returning the error:
<product sku="29043" category="audio" isFeatured="no" price="219.99">
<name>Sennheiser PC350 Gaming Stereo Headset</name>
<description>Gaming stereo headset, 10-26000Hz, 150ohm, 10-ft cord, noise-cancelling microphone.</description>
<colors>
<color>Black</color>
<color>Red</color>
</colors>
</product>
Here is my XSD file with the relevant sections:
<xs:attribute name="sku" type="xs:positiveInteger"/>
<xs:attribute name="category" type="section"/>
<xs:attribute name="isFeatured" type="yesno"/>
<xs:attribute name="price" type="money"/>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:simpleType name="section">
<xs:restriction base="xs:token">
<xs:enumeration value="audio"/>
<xs:enumeration value="appliance"/>
<xs:enumeration value="bathroom"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="yesno">
<xs:restriction base="xs:token">
<xs:enumeration value="yes"/>
<xs:enumeration value="no"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="money">
<xs:restriction base="xs:string">
<xs:pattern value='^[0-9]+.[0-9]{2}$'/>
</xs:restriction>
</xs:simpleType>
Any pointers? Can provide more info if needed.
Solution 1:[1]
XSD regex patterns require full string match, and ^ and $ are not parsed as anchors there.
You can use
<xs:simpleType name="money">
<xs:restriction base="xs:string">
<xs:pattern value='[0-9]+\.[0-9]{2}'/>
</xs:restriction>
</xs:simpleType>
This matches a string that starts with one or more digits ([0-9]+), then has a dot (\., note it should be escaped) and ends with two digits ([0-9]{2}).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Wiktor Stribiżew |
