gpt4 book ai didi

javascript - 将输入字段与模式匹配

转载 作者:行者123 更新时间:2023-11-30 17:20:46 25 4
gpt4 key购买 nike

我使用 java 脚本方法检查字段是否有效,以便表单可以继续。这在到达邮政编码之前工作正常,因为它必须是特定的模式。

有没有办法检查字段的值是否与模式匹配,然后允许表单继续。

如您所见,它设置为仅在长度大于 0 时才让表单前进,这对表单不利,但对邮政编码部分更糟。

Javascript:

function processPhase2(){
houseN = _("Hnumber").value;
lineone = _("Caddress1").value;
linetwo = _("Caddress2").value;
cityC = _("Ccity").value;
countyC = _("Ccounty").value;
postalcodeC = _("Cpostalcode").value;
if(houseN.length > 0 && lineone.length > 0 && cityC.length > 0 && countyC.length > 0 && postalcodeC.length > 0){
_("phase2").style.display = "none";
_("phase3").style.display = "block";
_("progressBar").value = 66;
_("status").innerHTML = "Phase 3 of 3";
} else {

}

输入框:

    <label for="postalcode">Postal Code</label>
<input type="text" name="Cpostalcode" id="Cpostalcode" size="20" required pattern="[A-Za-z]{1,2}[0-9Rr][0-9A-Za-z]? [0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}" placeholder="eg: W1C 8LT" title="Must match pattern">

最佳答案

使用 getAttribute 获取模式并将其应用于 new RegExp(pattern)。然后,您可以只使用 RegExp test方法。

var elem = document.getElementById("Cpostalcode");

var pattern = elem.getAttribute("pattern");
var re = new RegExp(pattern);
if (re.test(elem.value)) {
// Pattern matches!
} else {
// Pattern does NOT match.
}

JSFiddle


注意:您应该将开始 (^) 和结束 ($) 字符添加到您的模式,否则它将测试子字符串而不是测试整个字符串。您可以使用 var re = new RegExp("^"+pattern+"$") 或在 pattern 属性本身中执行此操作。 ( More on that... )

关于javascript - 将输入字段与模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25184469/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com