Skip to content

Instantly share code, notes, and snippets.

@trentrand
Last active July 30, 2024 18:31
Show Gist options
  • Save trentrand/f8f81d1441ca6579c80cc2a4ddbe7f81 to your computer and use it in GitHub Desktop.
Save trentrand/f8f81d1441ca6579c80cc2a4ddbe7f81 to your computer and use it in GitHub Desktop.
Regular expression for validating 'sms' uri scheme. (RFC 5724)[https://tools.ietf.org/html/rfc5724]
This protocol is well-defined by [RFC 5724][1] with the formal definition:
sms-uri = scheme ":" sms-hier-part [ "?" sms-fields ]
scheme = "sms"
sms-hier-part = sms-recipient *( "," sms-recipient )
sms-recipient = telephone-subscriber ; defined in RFC 3966
sms-fields = sms-field *( "&" sms-field )
sms-field = sms-field-name "=" escaped-value
sms-field-name = "body" / sms-field-ext ; "body" MUST only appear once
sms-field-ext = 1*( unreserved )
escaped-value = *( unreserved / pct-encoded ) ; defined in RFC 3986
The definition also provides three examples,
sms:+15105550101
This indicates an SMS-message-capable recipient at the given
telephone number. The message is sent using the user agent's default
SMS delivery method.
sms:+15105550101,+15105550102
This indicates SMS-message-capable recipients at the given telephone
numbers. The identical message should be sent to both recipients
using the user agent's default SMS delivery method.
sms:+15105550101?body=hello%20there
In this case, a message (initially being set to "hello there", which
may be modified by the user before sending) will be sent via SMS
using the user agent's default SMS delivery method.
---
**Working solution**
I've created the following regex that seems to loosely validate the formal definition:
`/^sms:([\+\-\(\)\d]*\d[\+\-\(\)\d]*,?)+([?&]body=.+)?$/`
**Test Cases**
This regex has produced correct validation against the following test cases:
```| Test case | Result | Expected Value |
|-----------------------------|---------|----------------|
| sms:1234567890 | Valid | Valid |
| sms:+1234567890 | Valid | Valid |
| sms:+1234567890,0987654321 | Valid | Valid |
| sms:+1-234-567-8901 | Valid | Valid |
| sms:+1234@#567890 | Invalid | Invalid |
| sms:+1234a567890 | Invalid | Invalid |
```
[1]: https://tools.ietf.org/html/rfc5724
@wprotheus
Copy link

Great job. Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment