JS验证中的正则表达式,替换和大写的问题

时间:2011-05-02 22:42:46

标签: javascript

我正在尝试在提交表单之前验证魁北克邮政编码。以下函数(onBlur)应该使字母大写并删除任何空格。 “别的”之前的一切都很好。

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());
        }
    }
}

这是由onSubmit事件触发的表单验证代码的一部分:

    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;
}

和HTML代码:

<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>

JS代码的两个部分都存在问题,因为当我更改字段框并且邮政编码有空格并且是小写字母时没有任何反应。此外,即使邮政编码的格式正确,我也会收到提醒。救命啊!

1 个答案:

答案 0 :(得分:2)

你不能匹配这样的正则表达式:

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

您需要.match.test。我喜欢比赛:

f.value.match(...)

我真的不知道那个正则表达式是什么......有很多/而没有\。 Je suis很困惑!

<强> PS
这是一个:http://regexlib.com/REDetails.aspx?regexp_id=570你必须爱Guugle!

如果是那个,你可以使用它:

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!'); }

虽然这个不完美(请注意无用的{1})......嘿,如果它有效,对吧!?

相关问题