Regex for custom validation | XM Community
Skip to main content
Solved

Regex for custom validation

  • 23 July 2024
  • 2 replies
  • 35 views

Hello,

 

I am looking to create a validation for a text entry. It is always 8 characters long, starting with a letter. However, it will either be one of the following:

  • 1 letter and 7 numbers (e.g., A1234567)
  • 2 letters and 6 numbers (e.g., AB123456)
  • 3 letters and 5 numbers (e.g., ABC12345)
  • 4 letters and 4 numbers (e.g., ABCD1234)

I tried a few options, but none seemed to work. Any help would be greatly appreciated! Thank you in advance.

2 replies

Userlevel 5
Badge +17

@woodsh Try this:

^[A-Za-z]{1}[0-9]{7}$|^[A-Za-z]{2}[0-9]{6}$|^[A-Za-z]{3}[0-9]{5}$|^[A-Za-z]{4}[0-9]{4}$

Some explanation:

- `^[A-Za-z]{1}[0-9]{7}$` matches a string with 1 letter followed by 7 digits.
- `^[A-Za-z]{2}[0-9]{6}$` matches a string with 2 letters followed by 6 digits.
- `^[A-Za-z]{3}[0-9]{5}$` matches a string with 3 letters followed by 5 digits.
- `^[A-Za-z]{4}[0-9]{4}$` matches a string with 4 letters followed by 4 digits.
- The `|` operator denotes an OR condition, allowing any one of the four patterns to match.

Badge +1

@woodsh Try this:

^[A-Za-z]{1}[0-9]{7}$|^[A-Za-z]{2}[0-9]{6}$|^[A-Za-z]{3}[0-9]{5}$|^[A-Za-z]{4}[0-9]{4}$

Some explanation:

- `^[A-Za-z]{1}[0-9]{7}$` matches a string with 1 letter followed by 7 digits.
- `^[A-Za-z]{2}[0-9]{6}$` matches a string with 2 letters followed by 6 digits.
- `^[A-Za-z]{3}[0-9]{5}$` matches a string with 3 letters followed by 5 digits.
- `^[A-Za-z]{4}[0-9]{4}$` matches a string with 4 letters followed by 4 digits.
- The `|` operator denotes an OR condition, allowing any one of the four patterns to match.

Thank you for this! My testing is showing this worked. I really appreciate you explaining it. I was able to adapt it from your explanation to fix another one that was causing some issues! 

Leave a Reply