ZVON > Tutorials > XML Schema and Relax NG Tutorial
Index | >> Example 5 / 8 << | Prev | Next |
Contents > Definition of own types > String must contain e-mail address

String must contain e-mail address

  1. XML Schema
  2. Relax NG
XML Schema keys: string, pattern

1. XML Schema

The element "A" must contain an email address. We will define our custom type, which will at least approximately check the validity of the address. We will use the "pattern" element, to restrict the string using regular expressions.

Valid document


<A xsi:noNamespaceSchemaLocation="correct_0.xsd" xmlns="" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >nobody@foo.org</A>

Invalid document
This won't be considered as valid e-mail address.


<A xsi:noNamespaceSchemaLocation="correct_0.xsd" xmlns="" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >xxx</A>

Invalid document
This won't be considered as valid e-mail address.


<A xsi:noNamespaceSchemaLocation="correct_0.xsd" xmlns="" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >@bar.com</A>

Invalid document
This won't be considered as valid e-mail address.


<A xsi:noNamespaceSchemaLocation="correct_0.xsd" xmlns="" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >abc@.bar.com</A>

Correct XML Schema (correct_0.xsd)


<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" >

  <xsd:element name="A" type="myString"/>

  <xsd:simpleType name="myString">
    <xsd:restriction base="xsd:string">
      <xsd:pattern value="[^@]+@[^\.]+\..+"/>
    </xsd:restriction>
  </xsd:simpleType>
</xsd:schema>

2. Relax NG

The element "A" must contain a string representing an e-mail address.

Valid document


<A xmlns="">nobody@foo.org</A>

Invalid document
This won't be considered as valid e-mail address.


<A xmlns="">xxx</A>

Invalid document
This won't be considered as valid e-mail address.


<A xmlns="">@bar.com</A>

Invalid document
This won't be considered as valid e-mail address.


<A xmlns="">abc@.bar.com</A>

Correct Relax NG schema (correctRelax_0.rng)


<grammar datatypeLibrary="http://www.w3.org/2001/XMLSchema-datatypes" xmlns="http://relaxng.org/ns/structure/1.0" >

  <start>
    <element>
      <name ns="">A</name>
      <ref name="myString"/>
    </element>
  </start>

  <define name="myString">
    <data type="string">
      <param name="pattern">[^@]+@[^\.]+\..+</param>
    </data>
  </define>
</grammar>