I want to validate name field which excepts only alphanumeric, apostrophe and a dot(.) For example, it should allow the string abc's home99
,St. Mary's Hospital
but I don't want the string starting with any of the special characters or ending with it for example 'abc
or abc'
or g_abc 56gfhg
or abc 56gfhg.
.
i have used
stringPattern = /^[a-zA-Z0-9']*$/;
pattern but it allows apostrophe anywhere in the string.
I want to validate name field which excepts only alphanumeric, apostrophe and a dot(.) For example, it should allow the string abc's home99
,St. Mary's Hospital
but I don't want the string starting with any of the special characters or ending with it for example 'abc
or abc'
or g_abc 56gfhg
or abc 56gfhg.
.
i have used
stringPattern = /^[a-zA-Z0-9']*$/;
pattern but it allows apostrophe anywhere in the string.
Share Improve this question edited Feb 4, 2014 at 10:32 Sonia asked Jan 20, 2014 at 6:07 SoniaSonia 451 silver badge9 bronze badges4 Answers
Reset to default 3try this regex:
\w(\w|'|\ )*\w
you can test it here: http://regexpal./
but it requires the username to be at least 2 characters long
var pattern = /^[^'][a-zA-Z0-9' ]*[^']$/;
console.log(pattern.exec("abc's home99"));
console.log(pattern.exec("'abc"));
console.log(pattern.exec("abc'"));
Output
[ 'abc\'s home99', index: 0, input: 'abc\'s home99' ]
null
null
In this Regular Expression, we say that, first character should not be '
(^[^']
) and the last character should not be '
([^']$
). You already had the rest :)
I'd do:
^\w+(?:[.' ]*\w+)*$
Explanation:
The regular expression:
^\w+(?:[.' ]*\w+)*$
matches as follows:
NODE EXPLANATION
----------------------------------------------------------------------
^ the beginning of the string
----------------------------------------------------------------------
\w+ word characters (a-z, A-Z, 0-9, _) (1 or
more times (matching the most amount
possible))
----------------------------------------------------------------------
(?: group, but do not capture (0 or more times
(matching the most amount possible)):
----------------------------------------------------------------------
[.' ]* any character of: '.', ''', ' ' (0 or
more times (matching the most amount
possible))
----------------------------------------------------------------------
\w+ word characters (a-z, A-Z, 0-9, _) (1 or
more times (matching the most amount
possible))
----------------------------------------------------------------------
)* end of grouping
----------------------------------------------------------------------
$ before an optional \n, and the end of the
string
----------------------------------------------------------------------
Try [A-Z,a-z,0-9,`-', ]* in pattern attribute of html input element. It will allow Letters,spaces,numbers,apostrophe and hyphen.