I'm calling a JavaScript DOM button click event to execute some code. However, I first need to validate if a textbox has a value in it. So, I'm using ASP.NET's RequiredFieldValidator control to validate the textbox. It works in that it will display an error message when the textbox is empty, however, the associated JavaScript button click event still fires.
How to do I prevent the JavaScript function from firing when I use an ASP.NET validation control?
By the way, I know I can use validation within JavaScript, but I'm hoping not to do that and just use ASP.NET validation controls only.
Here is my code (it's exactly how used with all the fluff removed):
<%@ Page Language="VB" blah... %>
<!DOCTYPE html>
<html lang="en">
<head runat="server">
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="MyButton" runat="server" Text="Click Me" />
<asp:TextBox runat="server" ID="MyTextBox"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ID="MyRequiredFieldValidator" ControlToValidate="MyTextBox" Display="Dynamic" Text="*" ErrorMessage="The field is required.">
Required
</asp:RequiredFieldValidator>
</form>
<script type="text/javascript">
$(document).ready(function () {
const vMYBUTTON = document.querySelector('#MyButton');
SomeKindOfPluginObject.dom.addEvent(vMYBUTTON, 'click', function () {
console.log('Function started.');
console.log('My code executed.');
console.log('Function ended.');
event.preventDefault();
});
});
</script>
</body>
</html>