How To Write A Regular Expression For Javascript Valiadation
Solution 1:
^[^ ]([\w- \.]+)[^ ]$
[^ ]
= cannot start or end with space
([\w- .]+)
= all characters allowed (or in this case, \w, hyphen, space and dot)
matches: ABC BCD
Solution 2:
I think it's clearer to separate the regex into multiple ones.
functionvalidate (str) {
if (/^\s|\s$/.test(str)) { // starts or ends with a spacereturnfalse;
}
if (/^-|-$/.test(str)) { // starts or ends with a hyphenreturnfalse;
}
return/[\s\w-]+/.test(str); // ensure all valid characters and non-empty
}
Solution 3:
I am not a 100% sure what you mean because in the allowed example values you have
MM 1.8.10
which does not follow the rule set you specified.
that is why I based the pattern on your example values, this should work
^[A-Z0-9]+(?:[ _.-][A-Z0-9]+){0,3}$
Explanation
^
start match at the beginning of the string
[A-Z0-9]+
match one or more uppercase alphanumeric characters, thus empty values will fail
(?:
start a non-capturing group, this group will allow a separator followed by again at least one alphanumeric uppercase character, which is mandatory, so the value must begin and end with alphanumeric characters and the separators are only allowed in between.
[ _.-]
match one space, underscore, dot or hyphen
[A-Z0-9]+
match one or more uppercase alphanumeric characters
)
close the non-capturing group
{0,3}
this allows the group to be matched 0 or up to 3 times.
$
match the end of the string
In the last part {0,3}$
the 3 is there to allow only up to 3 extra (so 4 in total) uppercase alphanumeric character groupings separated by a space, underscore, dot or hyphen, you can change the 3 into any digit you want or remove it to allow 0 or unlimited groupings.
Example script:
<scripttype="text/javascript">var strings = [
'ABC BCD',
'12345',
'ABC-12345',
'MM 1.8.10',
'530715 HS 9JAXXX4100',
'020-59898',
'HLXU1234'
]
var matches = '';
for(i = 0; i < strings.length; i++) {
matches += i + ' : ' + strings[i].match(/^[A-Z0-9]+(?:[ _.-][A-Z0-9]+){0,3}$/) + '\n';
}
window.alert(matches);
</script>
Post a Comment for "How To Write A Regular Expression For Javascript Valiadation"