Jesper
Jesper

Reputation: 999

Javascript Regex Problem with space

I am using this home-made function to validate text fields, but for some reason, it doesn't "accept" spaces. I find that weird, since I have \s in my class...

function validateText(controlid, minlength, maxlength, required) {
    var control = document.getElementById(controlid);
    if (!required && control.value.length == 0) control.style.backgroundColor = "White";
    else {
        var regex = new RegExp("^[a-zA-Z0-9\(\)\.\s_,:/-]{" + minlength + "," + maxlength + "}$", "g");
        if (!regex.test(control.value))
            control.style.backgroundColor = "#FFDDDD";
        else
            control.style.backgroundColor = "White";
    }
}

Can you tell me why entering a space turns the textbox red? Thanks :)

Upvotes: 1

Views: 305

Answers (1)

Sajid
Sajid

Reputation: 4421

I believe it's because you're trying to put \s in a class. Inside a class (eg, []) \s is simple a badly-escaped "s". Either use a literal space, or do ^([...]|\s){.

Upvotes: 3

Related Questions