
前端表单验证是Web开发中至关重要的一环。它不仅能提升用户体验,避免用户提交无效数据,还能减轻服务器压力,确保数据的有效性和安全性。本文将介绍如何使用JavaScript进行前端验证,并在验证失败时阻止表单提交,以及如何利用Ajax实现无刷新提交。
原问题中,表单的onsubmit事件绑定了一个validate()函数,期望在验证失败时阻止表单提交。然而,即使验证失败,表单仍然提交到了collect-dsrs-attendance-confirmation.php。这是因为validate()函数中存在逻辑问题,导致返回值不正确。
问题分析:
原代码中的validate()函数存在几个问题:
立即学习“前端免费学习笔记(深入)”;
解决方案:
以下是修改后的validate()函数,并添加了错误信息显示区域:
<div class="row">
<div class="col-12 col-md-12 col-sm-6">
<!-- Attendacne Card Info Fields-->
<div class="card">
<div class="card-body">
<!--<h4 class="card-title mb-5">DSR Information Fields</h4>-->
<form action="./collect-dsrs-attendance-confirmation.php" method="POST" name="page331" enctype="multipart/form-data" onsubmit="return validate();">
<div class="form-body">
<div class="row">
<input type="text" class="form-control" id="lat" name="latitude" style="display:none;" value="">
<input type="text" class="form-control" id="long" name="longitude" style="display:none;" value="">
<!--Back Button For Each Page-->
<div class="col-md-12 mb-5 d-grid gap-2 d-md-flex justify-content-md-end">
<div class="form-actions text-start mt-3">
<a type="button" href="./index.php" class="btn btn-danger ps-4 pe-4"
id="backhome" style="background-color: rgb(255, 0, 0);">Back Home</a>
</div>
</div>
<div class="col-lg-12 col-md-12">
<div class="form-group mb-3">
<label class="form-label text-dark" for="dsrELNumber">ইএল নম্বর</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon1">+880</span>
</div>
<input class="form-control" id="dsrELNumber" type="text" name="el_number" id="elNumber"
placeholder="Enter EL Number" data-maxlength="10" data-minlength="10"
oninput="this.value=this.value.slice(0,this.dataset.maxlength)"
value="<?php if(!empty($_POST['dsr_el_number'])) echo $_POST['el_number']; ?>" required>
</div>
<div id="docImage">
<!--<video id="video" width="640" height="480" autoplay style="display:none;"></video>-->
<label class="custom-file-label text-primary mt-3" for="file-input">Take Selfie</label>
<input type="file" class="mt-4 form-control" id="user_img" name="user_img" accept="image/*" capture="camera" required>
<button class="btn text-white mt-4 mb-4 d-block ps-4 pe-4" type="submit" style="background-color: rgb(255, 0, 0);" id="btnTakeDocument">Submit</button>
</div>
<!--Error Message-->
<div id="file_error" style="color:red;"></div>
<!--To show successfull message-->
<div id="message"></div>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
<!-- Attendacne Card Info Fields-->
</div>
</div>
<script>
function validate() {
var valid = true;
var file_name = "";
var file_type = "";
var file_size = "";
var error_msg = "";
var valid_size = 3 * 1000 * 1000;
var display_error = document.getElementById('file_error');
var file = document.getElementById("user_img");
if (file.files.length != 0) {
file_name = file.files[0].name;
file_size = file.files[0].size;
file_type = file.files[0].type;
if (file_type != "image/png" && file_type != "image/jpeg" && file_type != "image/gif") {
valid = false;
error_msg = error_msg + "\n* Only 'PNG', 'JPG/JPEG' and 'GIF' file type supported.";
}
if (file_size > valid_size) {
valid = false;
error_msg = error_msg + "\n* Filesize should be upto 3MB.";
}
} else {
valid = false;
error_msg = error_msg + "\n* Please select any image file.";
}
if (valid == true) {
alert("File pass all validation. Now it is ready to send.");
/*Write ajax code here to send file to the server.*/
return true;
} else {
display_error.innerHTML = error_msg;
return false;
}
}
</script>关键点:
虽然前端验证可以阻止大部分无效提交,但仍然可以通过绕过前端验证的方式提交数据。因此,结合后端验证是最佳实践。此外,使用Ajax可以实现无刷新提交,提升用户体验。
示例代码:
首先,移除表单的onsubmit事件,并添加一个按钮的点击事件监听器:
<form action="./collect-dsrs-attendance-confirmation.php" method="POST" name="page331" enctype="multipart/form-data">
...
<button class="btn text-white mt-4 mb-4 d-block ps-4 pe-4" type="button" style="background-color: rgb(255, 0, 0);" id="btnTakeDocument">Submit</button>
...
</form>然后,使用jQuery编写Ajax代码:
$(document).ready(function() {
$("#btnTakeDocument").click(function(e) {
e.preventDefault(); // 阻止默认的表单提交
if (!validate()) {
return; // 如果验证失败,则不提交
}
var formData = new FormData($('form[name="page331"]')[0]); // 使用FormData对象处理文件上传
$.ajax({
type: "POST",
url: "./collect-dsrs-attendance-confirmation.php",
data: formData,
contentType: false, // 必须设置为false
processData: false, // 必须设置为false
success: function(response) {
// 处理服务器返回的响应
$("#message").html(response); // 将响应显示在id为message的div中
alert("提交成功!");
},
error: function(xhr, status, error) {
// 处理错误
alert("提交失败:" + error);
}
});
});
});关键点:
后端验证:
在collect-dsrs-attendance-confirmation.php中,务必进行后端验证,确保数据的有效性和安全性。例如:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// 验证EL Number
if (!isset($_POST['el_number']) || !preg_match('/^\d{10}$/', $_POST['el_number'])) {
echo "EL Number 格式错误!";
exit;
}
// 验证文件上传
if (!isset($_FILES['user_img']) || $_FILES['user_img']['error'] !== UPLOAD_ERR_OK) {
echo "请选择上传的图片!";
exit;
}
$file_name = $_FILES['user_img']['name'];
$file_size = $_FILES['user_img']['size'];
$file_type = $_FILES['user_img']['type'];
$file_tmp_name = $_FILES['user_img']['tmp_name'];
if ($file_type != "image/png" && $file_type != "image/jpeg" && $file_type != "image/gif") {
echo "只支持 PNG、JPG/JPEG 和 GIF 格式的图片!";
exit;
}
if ($file_size > 3 * 1024 * 1024) {
echo "图片大小不能超过 3MB!";
exit;
}
// 将文件移动到指定目录
$upload_dir = "uploads/";
$target_file = $upload_dir . basename($file_name);
if (move_uploaded_file($file_tmp_name, $target_file)) {
echo "文件上传成功!";
} else {
echo "文件上传失败!";
}
}
?>总结:
通过结合前端验证和Ajax提交,可以有效防止无效数据提交,提升用户体验,并减轻服务器压力。前端验证可以快速反馈错误,而Ajax提交可以实现无刷新体验。同时,务必进行后端验证,确保数据的有效性和安全性。
以上就是前端表单验证与Ajax提交:防止无效数据提交的实用指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号