regex - Regular Expression for javascript to validate name and version -
i trying write regular expression in javascript. need validate name , version, following conditions:
name:
- only alphabets, no numbers , special characters
- no trailing spaces @ start or end, , no multiple spaces between words.
- minimum of 3 , maximum of 50 characters.
version:
- format should
[number].[number].[number]
- only single dot between numbers (
1.3..4
invalid,1.3.4
ok) - each number can of 1 or 2 digits,
1.11.26
(valid), not2.343.23
(invalid)
name
the regex
^(?! )((?! )(?! $)[a-za-z ]){3,50}$
only alphabets, no numbers , special characters => use character class that
[a-za-z]
no trailing spaces @ start or end, , no multiple spaces between words. => "anchoring" regex should thing on line , can't partially match. negative lookahead more 2 spaces not allowed
^...$ (?! )
no spaces @ beginning , and end => again can use lookaround
^(?! )...(?<! )$
but since javascript doesn't support lookbehind have use lookahead
(?! $)[a-za-z ]
minimum of 3 , maximum of 50 characters.
{3,50}
version
the regex
^\d{1,2}\.\d{1,2}\.\d{1,2}$
format should [number].[number].[number]
\d+\.\d+\.\d+
only single dot between numbers (1.3..4 invalid, 1.3.4 ok) => specifying \d digits allowed followed dot (which should escaped since otherwise mean character)
each number can of 1 or 2 digits, 1.11.26(valid), not 2.343.23 (invalid)
\d{1,2}
the last regex becomes following in javascript
if (/^\d{1,2}\.\d{1,2}\.\d{1,2}$/.test(subject)) { // successful match } else { // match attempt failed }
Comments
Post a Comment