Raphael Rafatpanah
Raphael Rafatpanah

Reputation: 20007

How to match this regex or null?

I have a javascript function that validates user input shown below:

function validateRugSize(rug_size) {
    var regex = /^(\d{1,2})(\')? (\d{1,2})("|\'\')? (x|X)? ?(\d{1,2})(\')? (\d{1,2})("|\'\')?$/;
    return regex.test(rug_size);
}

which gets called here:

if (!validateRugSize(rug_size[i])) {
    $("#SizeLabel" + i).text("Please enter a valid Rug Size.");
    $("#SizeLabel" + i).css("color", "red");
    $("#Size" + i).focus();
    return false;
} else {
    $("#SizeLabel" + i).text("");
}

I want the user's input to be valided only if a user enters a value there. I don't want to require input, however.

How can this be done?

Upvotes: 0

Views: 51

Answers (1)

Adrian B
Adrian B

Reputation: 1631

You need to add an extra condition:

if((rug_size[i].length > 0){
    if (!validateRugSize(rug_size[i])) {
        $("#SizeLabel" + i).text("Please enter a valid Rug Size.");
        $("#SizeLabel" + i).css("color", "red");
        $("#Size" + i).focus();
        return false;
    } else {
        $("#SizeLabel" + i).text("");
    }
}

Upvotes: 4

Related Questions