Usually, I’ll struggle through something for awhile before seeking help, but regex is just something I can’t completely wrap my head around. I’m hoping someone can help! Here’s the behaviors I’m looking for:
color hex values: allow only digits, lower/upper-case A-G, and “#”.
validate arbitrary number: is number between two given numbers, inclusive of the given numbers?
URLs: validate that the format of arbitrary URLs.
email: validate format of arbitrary email addresses.
phone numbers: remove everything except the “+” and digits 0-9.
latitude/longitude: allow only “-”, “.” and an arbitrary number of digits on either side of the decimal place.
I know this is a lot to ask, but without help, I could struggle with this for weeks and still have no success. I’ve learned my lesson with regex and hope someone’s feeling especially helpful today!
Don’t use regex for this one, just use int comparison (if ($x > 10 && $x < 20))
3 and 4) please google for those, there are lot’s of them out there
\+[0-9]+ (or if you know how many digits it should be, \+[0-9]{n} – where n is the number of digits it should be
\-?([0-9]\.[0-9]+|[0-9]+\.[0-9])
The last one is a bit more complicated to make sure they either put something in front of the dot, or put something after the dot, or both. Just a dot won’t validate.
Good question, thanks. They don’t have to be, no. I was thinking that would be the best way to validate data that follows a format, but contains arbitrary values. I’m certainly open to other approaches, especially if they save CPU!
Just a quick follow-up. Below are the patterns I ended up using; some from this thread, some from elsewhere on the net. I tried a lot of patterns and these were the most robust that I came across. Thanks again for the help.
Cheers!
// Validate format of email addresses.
// ^(\\w+@[a-zA-Z_]+?\\.[a-zA-Z]{2,6})^
// Validate format of phone numbers.
// ^(?:(?:\\+?1\\s*(?:[.-]\\s*)?)?(?:\\(\\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\\s*\\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\\s*(?:[.-]\\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\\s*(?:[.-]\\s*)?([0-9]{4})(?:\\s*(?:#|x\\.?|ext\\.?|extension)\\s*(\\d+))?$^
// Validate format of hexadecimal color values.
// ^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$^
// Validate format of latitude and longitude.
// ^\\-?([0-9]{1,10}\\.[0-9]{1,10}|[0-9]{1,10}\\.[0-9]{1,10})^
// Validate format of URLs.
// /^(https?):\\/\\/'.'(([a-z0-9$_\\.\\+!\\*\\'\\(\\),;\\?&=-]|%[0-9a-f]{2})+'.'(:([a-z0-9$_\\.\\+!\\*\\'\\(\\),;\\?&=-]|%[0-9a-f]{2})+)?'.'@)?(?#'.')((([a-z0-9][a-z0-9-]*[a-z0-9]\\.)*'.'[a-z][a-z0-9-]*[a-z0-9]'.'|((\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])\\.){3}'.'(\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])'.')(:\\d+)?'.')(((\\/+([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&=-]|%[0-9a-f]{2})*)*'.'(\\?([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&=-]|%[0-9a-f]{2})*)'.'?)?)?'.'(#([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&=-]|%[0-9a-f]{2})*)?'.'$/i