0

I want to do validation on element where it accepts either phone number or email address. I am using below pattern but its throwing schema validation issue.

[_\-a-zA-Z0-9\.\+][a-z|A-Z|0-9|@?](\.?[\-a-zA-Z0-9]*[a-zA-Z0-9])*

Expected result is this element accepts Ex: either 1234567890 or abc@gmail.com

Jon
  • 1
  • Try `([_a-zA-Z0-9.+-]*[a-zA-Z0-9]@[a-zA-Z0-9][_a-zA-Z0-9.+-]*(\.[-a-zA-Z0-9]*[a-zA-Z0-9])*|[0-9]+)`. I was trying to follow your pattern. If you are not married to this regex, you can try `(\S+@\S+\.\S+|[0-9]+)` – Wiktor Stribiżew Sep 07 '21 at 14:18

2 Answers2

0

Try

^(\d+|\w+@\w+\.com)$

Or

^(\d+|\w+@\w+\.\w+)$

Demo here.

Where

  • ^ - Match start of string
  • Outer (...) - Group where we will get either a number or an email
  • \d+ - Match only numbers
  • | - Or
  • \w+@\w+\.com - Match text that is separated by @ and ends with .com.
  • Your regex is producing below: – Jon Sep 07 '21 at 14:13
  • when I gave abc@gmail.com its giving abcgmail.com but I need regex which accepts either abc@gmail.com or 123456890 for a zelle element and it wont throw schema validation. – Jon Sep 07 '21 at 14:15
  • I'm not sure why the `@` sign was omitted as I tried it in [regex101](https://regex101.com/r/wGJ3uv/1) and it was captured. Perhaps you can try escaping the `@` sign by putting a slash `\@` and see what happens? – Niel Godfrey Pablo Ponciano Sep 07 '21 at 14:19
0

You should not specify both patterns in a single regex. XML Schema has a feature designed for exactly this purpose:

<xs:simpleType name="emailAddressType">
    <xs:restriction base="xs:string">
        <xs:pattern value="your chosen regex for an email address"/>
    </xs:restriction>
</xs:simpleType>

<xs:simpleType name="phoneNumberType">
    <xs:restriction base="xs:string">
        <xs:pattern value="your chosen regex for a phone number"/>
    </xs:restriction>
</xs:simpleType>

<xs:simpleType name="emailOrPhoneType"
    <xs:union memberTypes="emailAddressType phoneNumberType"/>
</xs:simpleType>

You may find this thread useful when choosing your regex for an email address: How to validate an email id in XML schema

kimbert
  • 2,376
  • 1
  • 10
  • 20
  • I tried this but this is failing for phone number always. Ex: 1234567890 or 123-456-7890 – Jon Sep 07 '21 at 17:43
  • @jon: please test your phone number regex separately (there are free regex testers online). When you have got it working, test with the full schema. And please, _please_ remember to quote error messages. Just saying 'it is failing' does not provide enough information. – kimbert Sep 08 '21 at 09:05