I have two events on my submit button. one is OnClientClick and second is OnClick. OnClientClick is used to validate form and OnClick is used to submit the record in database. firstly I want to validate the form and then it should be submitted. How to achieve this.
<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>`
Just add your client-side JavaScript code to the asp.net button “OnClientClick”.
So, your button can be written like this:
So, if your client side function validateSection4 returns true, then the button will submit, and your code stub (code behind) called cmdMySubMit_Click will run. If validateSection4() returns false, then the submit button will not post-back, and the code behind stub will not run.