我想驗證一些使用JS函數的表單字段,但是當點擊提交按鈕時他們似乎沒有加載或檢查字段。JS表單驗證不起作用
<html>
<body>
<?php require_once('logic.php'); ?>
<h1>Add new Region/Entity</h1>
<?php
if ($_POST['submitted']==1) {
echo $error;
}
?>
<form action="logic.php" method="post" name="registration" onSubmit="return formValidation();">
Region: <input type="text" name="region" value="<?php echo @$_POST['region']; ?>"><br>
Description: <br><textarea name="description" cols="50" rows="10"><?php echo @$_POST['description']; ?></textarea><br>
Remarks: <input type="text" name="remarks" value="<?php echo @$_POST['remarks']; ?>">
<input type="hidden" name="submitted" value="1"><br>
<input type="submit" value="Submit" onclick="">
而這裏的JS:
<script type="text/javascript">
function formValidation() {
var region = document.registration.region;
var descr = document.registration.description;
var remarks = document.registration.remarks;
if(empty_validation()) {
if(reg_validation()) {
if(reg_letters()) {
if (desc_letters()) {
if (desc_validation()) {
}
}
}
}
}
return false;
}
function empty_validation() {
var reg_len = region.value.length;
var descr_len = descr.value.length;
var rem_len = remarks.value.length;
if (reg_len == 0 || decr_len == 0 || rem_len == 0) {
alert("Please fill all the fields");
return false;
}
return true;
}
function reg_validation() {
if (reg_len > 50) {
alert("Only 50 characters are allowed in the Region field");
region.focus();
return false;
}
return true;
}
function reg_letters() {
var letters = /^[A-Za-z]+$/;
if(region.value.match(letters)) {
return true;
} else {
alert('Region field must have only alphabetical characters');
region.focus();
return false;
}
}
function desc_validation() {
if (descr_len > 500) {
alert("Only 500 characters are allowed in the description field");
descr.focus();
return false;
}
return true;
}
function desc_letters() {
var iChars = "[email protected]#$%^&*()+=-[]\\\';,./{}|\":<>?";
for (var i = 0; i < descr_len; i++) {
if (iChars.indexOf(descr.value.charAt(i)) != -1) {
alert ("Your description has special characters. \nThese are not allowed.\n Please remove them and try again.");
return false;
}
}
return true;
}
</script>
</form>
</body>
</html>
正如你所看到的,我是從形式到PHP文件發佈值。我已經使用表單標籤中的onSubmit
事件來初始化formValidation()
函數。由於某種原因,它不工作。
這裏的a working example如果你需要一個。
您是否嘗試過調試?驗證時出現錯誤 - 「區域未定義」:'var reg_len = region.value.length;' – Ian
它不工作!沒有幫助。預計什麼?發生什麼事? –
你不能在一個函數中聲明Javascript變量,然後期望它們在每個函數中都可用。你必須在每個函數中聲明它們才能使用它們。 – Ian