Josh G Josh G -5 years ago 116
jQuery Question

regular expression, not reading entire string

I have a standard expression that is not working correctly.
This expression is supposed to catch if a string has invalid characters anywhere in the string. It works perfect on but not in my tests.

The exp is:


It is failing on :

but passing with :

It should fail both times, what am I doing wrong?

matches nothing...

//All Boxs
$('input[type="text"]').each(function () {

var text = $(this).prop("value")
var textTest = /[a-zA-Z0-9'.\-]/g.test(text)

if (!textTest && text != "") {
allFieldsValid = false
$(this).css("background-color", "rgba(224, 0, 0, 0.29)")
alert("Invalid characters found in " + text + " \n\n Valid characters are:\n A-Z a-z 0-9 ' . -")
else {
$(this).css("background-color", "#FFFFFF")
$(this).prop("value", text)

edit:added code

Answer Source


You need to use

var textTest = /^[a-zA-Z0-9'.-]+$/.test(text)

Note the absence of /g modifier and the + quantifier. There are known issues when you use /g global modifier within a regex used in RegExp#test() function.

You may shorten it a bit with the help of the /i case insensitive modifier:

var textTest = /^[A-Z0-9'.-]+$/i.test(text)

Also, as I mention below, you do not have to escape the - at the end of the character class [...], but it is advisable to keep escaped if the pattern will be modified later by less regex-savvy developers.


Ok, say, you are using Regex.IsMatch(str, @"[a-zA-Z0-9'.-]"). The Regex.IsMatch searches for partial matches inside a string. So, if the input string contains an ASCII letter, digit, ', . or -, this will pass. Thus, it is logical that aa@#@# passes this test, and @#@# does not.

If you use the second one as Regex.IsMatch(str, @"^[a-zA-Z0-9'.-]$"), only 1 character strings (with an optional newline at the end) would get matched as ^ matches at the start of the string, [a-zA-Z0-9'.-] matches 1 character from the specified ranges/sets, and $ matches the end of the string (or right before the final newline).

So, you need a quantifier (+ to match 1 or more, or * to match zero or more occurrences) and the anchors \A and \z:

Regex.IsMatch(str, @"\A[a-zA-Z0-9'.-]+\z")
                     ^^              ^^^

\A matches the start of string (always) and \z matches the very end of the string in .NET. The [a-zA-Z0-9'.-]+ will match 1+ characters that are either ASCII letters, digits, ', . or -.

Note that - at the end of the character class does not have to be escaped (but you may keep the \- if some other developers will have to modify the pattern later).

And please be careful where you test your regexps. Regexr only supports JavaScript regex syntax. To test .NET regexps, use or RegexHero.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download