Blo*_*eeR 0 javascript validation
我试图用所谓的正则表达式验证邮政编码输入.以下是我的代码,由于某种原因似乎不起作用.我需要一个完全在纯JS中的解决方案,而不是在其他框架中.
function postalCodeValidate() {
var postalCode = document.getElementbyID("postalcode").value;
var errorMessage = document.getElementbyID("pcodeerror").innerHTML;
var postalPattern = /^\d{2}-\d{3}$/;
if (POSTALCODE == "") {
errorMessage = "You must enter a postal code!";
} else if (POSTALCODE.match(postalPattern) == null) {
errorMessage = "Wrong postal code format (00-000)";
}
}Run Code Online (Sandbox Code Playgroud)
<div class="frm">
<form>
<h5>Enter adress details</h5>
<div class="form-group">
<label for="postalcode">Postal Code</label>
<input type="text" class="form-control" id="postalcode" placeholder="Postal Code (00-000)">
<div id="pcodeerror"></div>
</div>
<button type="button" onclick="postalCodeValidate();" class="btn btn-primary">Submit</button>
<a href="#Register">
<h6>Register</h6>
</a>
</form>
</div>Run Code Online (Sandbox Code Playgroud)
你有一些问题:
POSTALCODE 不存在,JS区分大小写,所以POSTALCODE!== postalCode.
将字符串document.getElementById("pcodeerror").innerHTML赋值给变量然后为该变量分配消息不会更新document.getElementById("pcodeerror").innerHTML.所以,你需要了解参考是如何工作的,等等.
最后,您不需要该函数,match因为您没有使用返回的数组.因此,使用该函数test检查特定字符串上的正则表达式.
function postalCodeValidate() {
var postalCode = document.getElementById("postalcode").value;
var postalPattern = /^\d{2}-\d{3}$/;
if (postalCode == "") {
document.getElementById("pcodeerror").innerHTML = "You must enter a postal code!";
} else if (!postalPattern.test(postalCode)) {
document.getElementById("pcodeerror").innerHTML = "Wrong postal code format (00-000)";
}
}Run Code Online (Sandbox Code Playgroud)
body {
font-family: Roboto;
font-size: 18px;
background: #283c86;
/* fallback for old browsers */
background: -webkit-linear-gradient(to right, #45a247, #283c86);
/* Chrome 10-25, Safari 5.1-6 */
background: linear-gradient(to right, #45a247, #283c86);
/* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
}
.frm {
width: 50%;
height: auto;
margin: 0 auto;
width: 400px;
}
form {
margin-top: 30px;
background: #ebebe0;
padding: 20px 20px 40px 20px;
display: block;
border-radius: 20px;
}
.btn {
float: right;
}
#mailerror,
#passerror {
color: red;
}Run Code Online (Sandbox Code Playgroud)
<div class="frm">
<form>
<h5>Enter adress details</h5>
<div class="form-group">
<label for="postalcode">Postal Code</label>
<input type="text" class="form-control" id="postalcode" placeholder="Postal Code (00-000)">
<div id="pcodeerror"></div>
</div>
<button type="button" onclick="postalCodeValidate();" class="btn btn-primary">Submit</button>
<a href="#Register">
<h6>Register</h6>
</a>
</form>
</div>Run Code Online (Sandbox Code Playgroud)