提问人:Jayesh Shimpi 提问时间:7/28/2023 更新时间:7/29/2023 访问量:38
使用 javascript 验证 WebForm
Validation of WebForm using javascript
问:
我的提交按钮上有两个事件。一个是 OnClientClick,第二个是 OnClick。OnClientClick 用于验证表单,OnClick 用于在数据库中提交记录。首先,我想验证表格,然后应该提交。如何实现这一点。
<script type="text/javascript">
function validateSection4() {
var txtIDProof = document.getElementById('<%= txtIDProof.ClientID %>');
var txtIDNumber = document.getElementById('<%= txtIDNumber.ClientID %>');
var fileIDPhoto = document.getElementById('<%= fileIDPhoto.ClientID %>');
var file = fileIDPhoto.files[0]; // Get the selected file
var isValid = true;
var lblIDProof = document.getElementById('<%= lblIDProof.ClientID %>');
var lblIDNumber = document.getElementById('<%= lblIDNumber.ClientID %>');
var lblIDPhoto = document.getElementById('<%= lblIDPhoto.ClientID %>');
var allowedExtensions = ["jpeg", "jpg", "png"];
var maxFileSize = 100 * 1024; // 100 KB in bytes
// Clear previous error messages
document.getElementById("lblIDProof").innerText = "";
document.getElementById("lblIDNumber").innerText = "";
document.getElementById("lblIDPhoto").innerText = "";
// Validate ID Proof dropdown
if (txtIDProof.value.trim() === '') {
lblIDProof.innerHTML = 'Please select an ID Proof.';
isValid = false;
}
// Validate ID Number textbox
if (txtIDNumber.value.trim() === '') {
lblIDNumber.innerHTML = 'Please enter the ID Number.';
isValid = false;
}
// Validate ID Photo upload
if (fileIDPhoto.files.length === 0) {
lblIDPhoto.innerHTML = 'Please upload the ID Photo.';
isValid = false;
}
else {
var fileExtension = file.name.split('.').pop().toLowerCase();
var fileSize = file.size;
// Check file extension
if (!allowedExtensions.includes(fileExtension)) {
lblIDPhoto.innerHTML = 'Only jpeg, jpg, and png files are allowed.';
isValid = false;
}
// Check file size
if (fileSize > maxFileSize) {
lblIDPhoto.innerHTML = 'Maximum file size allowed is 100KB.';
isValid = false;
}
}
return isValid;
}
</script>`
答:
0赞
Albert D. Kallal
7/29/2023
#1
只需将客户端 JavaScript 代码添加到 asp.net 按钮“OnClientClick”即可。
所以,你的按钮可以这样写:
<asp:Button ID="cmdMySubMit" runat="server"
Text="Submit"
OnClick="cmdMySubMit_Click"
OnClientClick="return validateSection4()"
/>
因此,如果客户端函数 validateSection4 返回 true,则该按钮将提交,并且名为 cmdMySubMit_Click 的代码存根(代码隐藏)将运行。 如果 validateSection4() 返回 false,则提交按钮将不会回发,并且存根背后的代码将不会运行。
评论