Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript regex to validate alphanumeric text with spaces and reject special characters

I'm not an expert with regex but tried my hand with validating a field that allows alphanumeric data with spaces but not any other special characters. Where linkTitle is the name of the variable to test i tried with the following regex in my conditional

/[^A-Za-z\d\s]/.test(linkTitle)
/[^A-Za-z0-9\s]/.test(linkTitle)
/[^A-Za-z\d ]/.test(linkTitle)

and none of these worked... i'm curious to know what went wrong with the regex using \s which seemingly refers whitespaces and what would be the apt regex to fit the bill.

Thanks in advance!!

like image 430
optimusprime619 Avatar asked Dec 16 '11 15:12

optimusprime619


1 Answers

I think you want to match the beginning of the string once, then use the Positive Closure—one or more—of your letters, spaces or digits, then the end of the string.

/^[A-Za-z\d\s]+$/.test(linkTitle)

Tested with:

var reg = /^[A-Za-z\d\s]+$/;
["Adam", "Ada m", "A1dam", "A!dam", 'sdasd 213123&*&*&'].forEach(function (str) {
    console.log(reg.test(str + "\n"));
});

Shows true, true, true, false, false


Or if you want to allow empty strings, you could use the same RegEx but with the Kleene Closure—zero or more—of letters, digits or spaces

var regAllowEmpty = /^[A-Za-z\d\s]*$/;
["", "Adam", "Ada m", "A1dam", "A!dam", 'sdasd 213123&*&*&'].forEach(function (str) {
    console.log(regAllowEmpty.test(str + "\n"));
}); 

note that forEach will not work on older browsers - this is just for testing

like image 140
Adam Rackis Avatar answered Nov 03 '22 11:11

Adam Rackis