Ramakrishnan
Ramakrishnan

Reputation: 5436

XSD Element Not Null or Empty Constraint For Xml?

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

Answers (6)

codesniffer
codesniffer

Reputation: 1180

My 2 solutions:

  1. Use 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>
  1. Use 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

mrx
mrx

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

Kamal
Kamal

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

Gab
Gab

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

sri
sri

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

Nic Gibson
Nic Gibson

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

Related Questions