Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS regex string validation for slug

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 ?

like image 322
KodeFor.Me Avatar asked Mar 17 '14 12:03

KodeFor.Me


3 Answers

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 ! :)

like image 97
user3427495 Avatar answered Nov 02 '22 13:11

user3427495


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.

like image 28
Thibault Lemaire Avatar answered Nov 02 '22 12:11

Thibault Lemaire


^[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.

like image 24
aelor Avatar answered Nov 02 '22 12:11

aelor