1

I really want it to format like this (999) 999-9999, but somehow it isn't working.

<xsd:simpleType name="TelephoneType">
    <xsd:restriction base="xsd:string">
         <xsd:pattern value="(\d{3}) \d{3}-\d{4}"/>
    </xsd:restriction>
</xsd:simpleType>

I also tried this and it didn't work:

<xsd:simpleType name="TelephoneType">
    <xsd:restriction base="xsd:string">
         <xsd:pattern value="([0-9]{3}) [0-9]{3}-[0-9]{4}"/>
    </xsd:restriction>
</xsd:simpleType>
kjhughes
  • 106,133
  • 27
  • 181
  • 240
JReyes
  • 13
  • 1
  • 3
  • 1
    Are you really sure that your data will only ever include people in North America? Because personally, I'm fed up with web sites where I have to give a false phone number in order to get past idiotic validation rules like this. – Michael Kay May 03 '16 at 07:37
  • @kjhughes - good one. I think schema validation really not so valuable, and frequently becomes an unnecessary hurdle implemented by beginner XML developers. Especially at this low level (phone # formatting) it's really not useful and limits future expansion. Would you really want to reject a transaction, because a phone # is missing space or other punctuation? Maybe not? – William Walseth May 03 '16 at 15:58
  • 2
    @WilliamWalseth: Where/when to perform validation checks, how strict to be about them, whether they should be geographically general, and what the ideal normalized form for storage/exchange should be are all valid concerns that can't be conveyed to a beginner by "*step away from the schema...*" Your comment is unconstructive and should be deleted. – kjhughes May 03 '16 at 16:47

1 Answers1

2

Specific regex solution

Escape the parentheses that you wish to literally appear in the phone number:

    <xsd:pattern value="\(\d{3}\) \d{3}-\d{4}"/>

or

    <xsd:pattern value="\([0-9]{3}\) [0-9]{3}-[0-9]{4}"/>

then either pattern will match phone numbers of the requested form.

General design considerations

The above solution addresses your specific question, however, keep in mind that phone numbers are often written in many other ways than (999) 999-9999, both in the US and internationally. This topic is addressed in this question on Stack Overflow: A comprehensive regex for phone number validation.

A more robust design would select a general, normalized format for storage and exchange as declared in the XSD. Providers of this data would be responsible for converting from acceptable conventions to the normalized form. It also can be useful to separately track the data in the provided form, even if it cannot be automatically converted to the normalized form, in cases where lax or partial validation is acceptable prior to transmission or storage.

Community
  • 1
  • 1
kjhughes
  • 106,133
  • 27
  • 181
  • 240
  • 1
    Thanks this worked perfectly:)and I just wanted to know how to format it this way cause I am messing around with different formats and I got stuck with this one. – JReyes May 05 '16 at 00:36