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