0

How can I use XSLT 2.0 to validate an email-address? Is there a predefined method or do I have to build a regex-expression?

Thanks

Mathias Bader
  • 3,585
  • 7
  • 39
  • 61
  • You can't build a regex for Email-validation yourself. But you could use one that is publicly available. – Vince Oct 11 '13 at 12:23
  • @Vince: Thanks for your comment. So I guess there is no pre-defined method or a method in an available framework? – Mathias Bader Oct 11 '13 at 12:25
  • I don't know about xslt, but if there is, I'm pretty sure, you'd find it in the documentation/google somewhere. – Vince Oct 11 '13 at 12:26

2 Answers2

6

You can do this in XSLT 2.0 but you will have to use a regular expression (although writing a regular expression that can actually match all possible email addresses is another matter).

In the case of using a regular expression, you would use the matches function to check if a string matches the regular expression for an email address (where $email is a variable containing the string to validate. Alternatively you could use element name containing the email address).

<xsl:if test="matches(upper-case($email),'^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$')">
   Valid
</xsl:if>

Check out http://www.xml.com/pub/a/2003/06/04/tr.html for information on regular expressions.

Note that I got the regular expression from this example from http://www.regular-expressions.info/email.html. In this case, it assumed it was upper-case, hence the use of the function in my example.

Tim C
  • 70,053
  • 14
  • 74
  • 93
  • Thank you Tim, that helps a lot. – Mathias Bader Oct 12 '13 at 15:56
  • Note that to support all possible emails, you'd have to use a slightly more complicated regular expression: http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address/1917982#1917982 – Alexis Wilke Mar 22 '14 at 05:09
0

Yes, you can use XPath 2.0's match() function in XSLT 2.0 to test a candidate email address against a regular expression.

However, whether it is a good idea to use regular expressions to validate an email address is another question. See the cited SO question and answers for candidate regular expressions as well as warnings about the limitations of using regular expressions to validate emails addresses in general.

Community
  • 1
  • 1
kjhughes
  • 106,133
  • 27
  • 181
  • 240