Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
86
rated 0 times [  91] [ 5]  / answers: 1 / hits: 20966  / 11 Years ago, thu, january 16, 2014, 12:00:00

I would like to all alphanumeric data +
only these following 4 special character are allowed.



' (single quote)
- (hyphen)
. (dot)
single space


I tried this :



var userinput = $(this).val();
var pattern = [A-Za-z0-9_~-!@#$%^&*()]+$

if(!pattern.test(userinput))
{
alert('not a valid');
}​


but it is not working.


More From » jquery

 Answers
15

First, you need to enclose the string in / to have it interpreted as a regex:



var pattern = /[A-Za-z0-9_~-!@#$%^&*()]+$/;


Then, you have to remove some unallowed characters (that regex is matching more than you specified):



var pattern = /^[A-Za-z0-9 '.-]+$/;


The second one is what you need. Complete code:



var userinput = $(this).val();
var pattern = /^[A-Za-z0-9 '.-]+$/;

if(!pattern.test(userinput))
{
alert('not a valid');
}​


Besides, check what this points to.


[#73125] Wednesday, January 15, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
serena

Total Points: 488
Total Questions: 125
Total Answers: 114

Location: Estonia
Member since Wed, Jun 8, 2022
2 Years ago
;