如何使用锚标记进行所需的字段文件上传验证?



我正在使用带有锚标记的jquery对文件上传字段进行客户端验证。但是表格是在验证之前提交的,或者可能是我错过了一些东西..任何人都可以帮我解决这个问题吗?

{% extends "base.html" %}
{% block content %}
<div class="container" xmlns="http://www.w3.org/1999/html">
<div class="row">
<div class="col-sm-6 banner-imageicon">
<img src="/static/images/data.png" class="img-responsive">
</div>
<div class="col-sm-6 banner-info">
<p class="big-text"> Excel Data Consolidation for Format 7</p>
</div>
<br>
<h2 align="center">Below are the fields which will be added in the consolidates format:</h2>
<p align ="center">Port of Loading (POL) and Origin City</p>
<p align="center">Port of Destination and Destination City</p>
<p align="center">Effective Date</p>
<p align="center">Freight Charges</p>
<p align="center">Expiry Date</p>
<p align="center">Surcharges Not Subject to</p>
<p align="right" class="Note">Note: By default commodity field is filled with the value-MSCUFAKOO1.</p>
<form method="POST" enctype="multipart/form-data"  id="frm" name="frm">
{% csrf_token %}
<p align="center"><h3>Choose the file whose data has to be consolidated</h3></p>
<label for="file-upload" align="center">Browse....</label>
<input type="file" id="file-upload" name="file" style="display:none;"  align="center" required>
<div id="file-upload-filename"></div>
<div class="button">
<a class="btn btn-first" href="#" id="submit"  onclick="document.getElementById('frm').submit()">Submit</a>
<a class="btn btn-second" href="" onclick="document.getElementById('frm').reset()">Reset</a>
</div>
</form>
<script src="/static/js/jquery.js"></script>
<script src="/static/js/jquery.validate.js"></script>
<script src="/static/js/additional-methods.js"></script>
<script>
$(document).ready(function(){
console.log("from function")
$("#frm").validate({
ignore:[],
rules:{
file:{
required:true,
}
},
messages:{
file:{
required:"Please select the file"
}
},
submitHandler: function(form) {
}
});
$("#submit").click(function(e) {
e.preventDefault();
console.log("from submit");
$("#frm").submit();
});
});
</script>
<script>
var input = document.getElementById( 'file-upload' );
var infoArea = document.getElementById( 'file-upload-filename' );
input.addEventListener( 'change', showFileName );
function showFileName( event ) {
var input = event.srcElement;
var fileName = input.files[0].name;
infoArea.textContent = 'File name: ' + fileName;
}
</script>
</div>
</div>
{% endblock content %}

如果表单在选择文件之前提交,我希望显示验证消息。但是验证不起作用。

我想你错过了html部分中的"经典"onsubmit属性。

<form action="/action_page.php" onsubmit="myFunction()">
Enter name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
<script>
function myFunction() {
alert("The form was submitted");
}
</script>

另一种方法是编写一个自定义函数,该函数读出表单并在读取值后进行检查。然后,您还必须自己执行发送请求。好处:现在也可以通过 ajax 或工作线程任务来完成。当然,您可以摆脱一些草率的编码html表单构造问题。

最新更新