I have an app, that allowing the end user to enter his desired slug. What I am looking for is a regex that check if the slug is valid.
In general, as valid a mean a string that start and ends with a latin leter, divided by dashes but not more than one dashes.
More specific, the following is correct:
one-two-three
The following are not:
one---two-thee-
-one-two-three
one-two-three-
So with the following regex I am somewhow ok, but how can I check if in the middle of the string there are no more than two dashes ?
^[a-z][a-z][a-z]$
Is there a better way to write this regex, in order to meet my validation creteria ?
http://regexpal.com/ can be a great webpage for checking your regexes as you write them. A handy tool :).
Having a look at yours, should it accept capital letters/numbers? If so maybe this will help :
/^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$/
This will only match sequences of one or more sequences of alphanumeric characters separated by a single -. If you do not want to allow single words (e.g. just hello), replace the * multiplier with + to allow only one or more repetitions of the last group.
Here's a link to a live sample from the same thread to demonstrate.
Changing around the A-Za-z0-9 inside the squares will allow you to only accept capitals,non-capitals or numbers as is appropriate to you.
Good luck and let me know if you have any more questions ! :)
My personal favourite :
^[a-z](-?[a-z])*$
Begin with a lowercase letter; then more lower or maybe a hyphen, but not without another lower right after it.
^[a-z][a-z\-]*[a-z]$
actually this should be your regex and your validation should be tested in two phases.
The first one by this regex, which will be a basic test, the second one can be done by splitting on hiphens and checking again the same regex on the splitted strings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With