Reputation: 5436
This is my sample XML Code:
<bestContact>
<firstName><![CDATA[12345]]></firstName>
<lastName />
</bestContact>
I am using:
<xs:element name="lastName" type="xs:string" minOccurs="1" nillable="false"/>
The XSD Should be validate lastName
as not null or empty.
Upvotes: 28
Views: 74894
Reputation: 1180
My 2 solutions:
xs:token
so leading & trailing spaces are ignored and a minimum length of 1: <xs:simpleType name="NonEmptyElementType">
<xs:restriction base="xs:token">
<xs:minLength value="1"/>
</xs:restriction>
</xs:simpleType>
xs:string
so leading & trailing spaces are permitted, and a simple regex to verify at least one non-whitespace character is present (in this solution the <xs:minLength value="1"/>
is not necessary, but I like the readability of it for future maintainers.): <xs:simpleType name="NonEmptyElementType">
<xs:restriction base="xs:string">
<xs:minLength value="1"/>
<xs:pattern value=".*\S.*"/>
</xs:restriction>
</xs:simpleType>
Upvotes: 0
Reputation: 1
This was my favourite solution.
<xs:simpleType name="NonEmptyString">
<xs:restriction base="xs:string">
<xs:pattern value="[\s\S]*[^ ][\s\S]*"/>
</xs:restriction>
</xs:simpleType>
Upvotes: 0
Reputation: 2522
Try
<xs:element name="lastName" minOccurs="1" nillable="false">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:minLength value="1"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
Upvotes: 61
Reputation: 8332
This is IMHO a better pattern:
<xs:simpleType name="NonEmptyString">
<xs:restriction base="xs:string">
<xs:pattern value="^(?!\s*$).+" />
</xs:restriction>
</xs:simpleType>
or
<xs:simpleType name="NonEmptyStringWithoutSpace">
<xs:restriction base="xs:string">
<xs:pattern value="\S+"/>
</xs:restriction>
</xs:simpleType>
Upvotes: 11
Reputation: 221
<xsd:element name="lastName" type="NonEmptyString" nillable="false"/>
<xsd:simpleType name="NonEmptyString">
<xsd:restriction base="xs:string">
<xsd:minLength value="1" />
<xsd:pattern value=".*[^\s].*" />
</xsd:restriction>
</xsd:simpleType>
Upvotes: 22
Reputation: 7143
@Kamal has given you basically right answer here. This is why - nillable
always seems to cause problems. Effectively, you can consider nillable
as meaning allow the xsi:nil
attribute on this element. The XML Schema spec describes nillable as an out of band signal - it's basically used to indicate NULL to databases.
What you want is an element that must be at least one character long as given by @Kamal
Upvotes: 9