0
這是我的代碼,我無法弄清楚它在哪裏壞了。它的運行方式就好像它從不檢查寫入的正確正則表達式的變量。任何幫助搞清楚哪裏會出錯將不勝感激。表單驗證不檢查表達式
<script>
function allNumbers(field, msg) {
var numberexp = /^[0-9]+$/;
if (field.value.match(numberexp)) {
return true;
} else {
alert(msg);
field.focus();
return false;
}
}
function allLetters(field, msg) {
var letexp = /^[a-zA-Z]+$/;
if (field.value.match(letexp)) {
return true;
} else {
alert(Msg);
field.focus();
return false;
}
}
function notEmpty(field, msg) {
if (field.value.length == 0) {
alert(msg);
field.focus();
return false;
}
return true;
}
function validateForm() {
var a = document.getElementById('firstname');
var b = document.forms["contactrecord"]["lastname"].value;
var c = document.forms["contactrecord"]["phone"].value;
var d = document.forms["contactrecord"]["address"].value;
var e = document.forms["contactrecord"]["city"].value;
var f = document.forms["contactrecord"]["state"].value;
var g = document.forms["contactrecord"]["zip"].value;
if (allLetters(a, "Incorrect First Name")) {
if (allLetters(b, "Incorrect Last Name")) {
if (allNumbers(c, "Incorrect Phone Number")) {
if (notEmpty(d, "Incorrect address")) {
if (allLetters(e, "Incorrect City Name")) {
if (allNumbers(g, "Incorrect Zip Code")) {
return true;
}
}
}
}
}
}
return false;
}
</script>
而不是*匹配*,它更適合使用*測試*,如:'numberexp.test (field.value)'。數字正則表達式可以是'/^\ d + $ /'或否定'/ \ D /'和字母'/^\ w + $ /'或否定'/ \ W /'。 – RobG
@RobG這應該不重要。你需要爲你的HTML中的'lastname','phone','address','city','state'和'zip'設置'name'屬性,比如'' 。你做? – PHPglue
@ PHPglue - 這是一條評論,而不是解決方案。如果提交表格,但ID可能會需要名稱。我寧願處理我能看到的問題,而不去猜測我不能做的事情。 – RobG