I have used the below regex expression to check alphabets, numbers, characters, + and –
if (/[^a-z0-9\-\+]+$/i.test(value))
{
alert ("Only alphabets and numbers are allowed.");
return;
}
This shows the message if any special characters is used. But one problem i am facing is if the value is a combination of special characters and alphabets or numbers then this condition does not satisfy. For example if the value is %$2 then the condition does not return true and show the message. I want that if any special character is present then the condition should satisfy and show the message.
You should not use the
$anchor. Also the final+is not necessary in your case. The following checks whether the string contains any disallowed characters:You could also invert the condition. (Use
*or+depending on whether you allow empty string.) The following checks whether the whole string only contains the allowed characters: