Basic Search  Advanced Search   
Topics Resources Free Library Software XML News About Us
home » info bank » Ask Team Mon, Aug 13, 2007
How do I validate email address using XSD Schema? I have an element in XML document that contains email address, I am already validating this XML file using XSD schema file. I would like to add an extra check to make sure that the email element contains an email address in a proper format.
You can use regular expressions alongwith xsd:pattern tag to do things like this (email validation, date validation, etc.).

Here is a sample XSD schema for an XML document that contains only one element named Email and it makes sure that this element contains a valid email address. The XSD file does this by defining xsd:restriction containing xsd:pattern and the pattern value is the regular expression used to validate the email address format.
<xsd:schema xmlns:xsd="">

  <xsd:element name="Email" type="EmailType" />

  <xsd:simpleType name="EmailType" >
    <xsd:restriction base="xsd:token">
      <xsd:pattern value="([\.a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(([a-zA-Z0-9_-])*\.([a-zA-Z0-9_-])+)+"/>

Sample XML document
<Email>[email protected]</Email>
Sample Visual Basic code that uses MSXML for XSD Schema Validation
  Dim objSchemaCache As New MSXML2.XMLSchemaCache40
  objSchemaCache.Add "", "c:\EmailValidation.xsd"
  Dim objXMLDoc As New MSXML2.DOMDocument40
  Set objXMLDoc.schemas = objSchemaCache
  objXMLDoc.async = False
  objXMLDoc.Load "c:\Email.xml"
  'MsgBox objXMLDoc.xml
  If objXMLDoc.parseError.errorCode <> 0 Then
    MsgBox "Email Validation Failed: " & _
      objXMLDoc.parseError.errorCode & " " & _
    MsgBox "Validation succeeded.  No Error."
  End If
Try changing the email value in the sample XML document and run the above VB code (make sure to add reference to MSXML 4.0) and see how the email validation is done using XSD schemas.

Related links:

  Contact Us |  | Site Guide | About PerfectXML | Advertise ©2004 All rights reserved. | Privacy