开发者

Problem with regexp, replace and ToUppercase in JS validation

I am trying validate a Quebec postal code before a form is submitted. The following function (onBlur) is supposed to make the letters uppercase and remove any white space. Everything before the "else" works fine.

function back2(that){
    if (that.value.length <=4) {
        that.value = that.getAttribute("default");
        that.setAttribute("class", "exemple");
    } else {
        if (that.getAttribute("id") == 'zip') {
            that.setAttribute("value", that.value.replace(/\s/g, ""));
            that.setAttribute("value", that.value.toUpperCase());
        }
    }
}

This is part of the form validation code triggered by an o开发者_如何学JAVAnSubmit event:

    if (f.value != "^G//d//D//d//D//d$" || 
        f.value != "^H//d//D//d//D//d$" ||
        f.value != "^J//d//D//d//D//d$" ||
        f.value != "^K1//D//d//D//d$" ||
        f.length !=6 ) {
        alert("Veuillez mettre un code postal valide du Québec, merci.");
        return false;
    }
    return true;
}

and HTML code:

<td>Code Postal</td>
<td><input name="zip" type="text"
     id="zip" value="J0B4M1" size="35"
     class="exemple" onfocus="clean(this)"
     onblur="back2(this)" default="J0B4M1"></td>

There are problems in both parts of JS code because nothing happens when I change field boxes and the postal code has spaces and is in lowercase letters. Also, I get an alert even if the format of the postal code is correct. Help!


You can't match a regex like this:

f.value != "^G//d//D//d//D//d$"

You'll need .match or .test. I like match:

f.value.match(...)

I really don't know what that regex is though... There's a lot of / and no \. Je suis confused!

PS
Is this the one: http://regexlib.com/REDetails.aspx?regexp_id=570 You gotta love the Guugle!

If that is the one, you could use this:

if ( !f.value.match(/^[a-zA-Z]{1}[0-9]{1}[a-zA-Z]{1}(\-| |){1}[0-9]{1}[a-zA-Z]{1}[0-9]{1}$/) ) { alert('Oy! That\'s not right!'); }

Although this one is not perfect (note the useless {1})... Hey if it works, right!?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜