Implementing validation in ASP.Net along with JavaScript for both the update and cancel buttons

My main objective is to show a message during the server roundtrip of an ASP.Net WebForm. Within my WebForm, there are two buttons: an update button and a cancel button. The message should always appear if either the update button or the cancel button is clicked. When the update button is clicked, the TextBox must be validated to ensure it contains a value. Below is the code snippet I am working with:

<%@ Page Language="VB" %>
<!DOCTYPE html>
<script runat="server">
    Protected Sub ButtonValidated_Click(sender As Object, e As EventArgs)
        Label1.Text = "ButtonValidated " & Now.ToLongTimeString & " " & TextBox1.Text
    End Sub

    Protected Sub ButtonUnvalidated_Click(sender As Object, e As EventArgs)
        Label1.Text = "ButtonUnvalidated " & Now.ToLongTimeString & " " & TextBox1.Text
    End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Validators and JS</title>
    <script type="text/javascript">
        function ShowValMsg(e, val) {
            dv = $get("ProgressDiv");
            var r = true;
            if (val != null) {
                r = Page_ClientValidate(val);
                if (r) {
                    dv = $get("ProgressDiv");
                    dv.style.visibility = "visible";
                }
            } else {
                dv = $get("ProgressDiv");
                dv.style.visibility = "visible";
            }
            return r;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
    <div>
        <asp:TextBox ID="TextBox1" runat="server" />
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="RequiredFieldValidator" ControlToValidate="TextBox1" ValidationGroup="ValGrp" />
        <br />
        <!-- this could be the update button -->
        <asp:Button ID="ButtonJsValidated" runat="server" Text="JsValidated" OnClick="ButtonValidated_Click" CausesValidation="false" OnClientClick="return ShowValMsg(this, &quot;ValGrp&quot;);" />
        <!-- this could be the cancel button -->
        <asp:Button ID="ButtonJsUnvalidated" runat="server" Text="JsUnvalidated" OnClick="ButtonUnvalidated_Click"  CausesValidation="false" OnClientClick="return ShowValMsg(this, null);" />
        <br />
        <asp:Button ID="ButtonValidated" runat="server" Text="Validated" OnClick="ButtonValidated_Click" CausesValidation="true" ValidationGroup="ValGrp" />
        <asp:Button ID="ButtonUnvalidated" runat="server" Text="Unvalidated" OnClick="ButtonUnvalidated_Click" CausesValidation="false" />
        <br />
        <asp:Label ID="Label1" runat="server" Text="Label" />
        <div id="ProgressDiv" style="position:absolute;top:0px;left:300px;height:100px;width:100px;visibility:hidden;opacity: 1; z-index: auto" >Please wait ...</div>
    </div>
    </form>
</body>
</html>

If TextBox1 is empty and I click on ButtonValidated, followed by ButtonJsUnvalidated, it functions as intended. If TextBox1 is empty and I click on ButtonJsValidated, then press ButtonJsUnvalidated, there is no server roundtrip. However, on clicking ButtonJsUnvalidated again, it works properly. Therefore, it seems like something goes wrong when clicking on ButtonJsValidated. I have searched for solutions related to revalidation upon clicking the same button again or resetting validators but have not been successful.

Does anyone have a solution?

Answer №1

Big shoutout to Hannes over at ppedv.de for providing me with the perfect solution! Here’s how my JS code now looks:

        function ShowValMsg(e, val, msg) {
            if (msg == null) {
                if (val != null) {
                    if (Page_ClientValidate(val)) {
                        Show(e);
                    }
                    return;
                } else {
                    Show(e);
                    return;
                }
            } else {
                if (val != null) {
                    if (Page_ClientValidate(val)) {
                        if (confirm(msg)) {
                            Show(e);
                            return;
                        } else {
                            return false;
                        }
                    }
                } else {
                    if (confirm(msg)) {
                        Show(e);
                        return;
                    } else {
                        return false;
                    }
                }
            }
        }

        function Show(e) {
            $get("ProgressDiv").style.visibility = "visible";
        }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporating a TypeScript module into a JavaScript module within a React application

I'm encountering an issue with my React app that was created using create-react-app. I recently added a Typescript module to the project, which is necessary for functionality reasons. Although it will remain in Typescript, I made sure to install all t ...

Using AngularJS to modify a record

I am currently developing a web application using C# with angularjs. Within my app, I have multiple records that I need to update. I have set up the necessary web service and included the required JS files for updating these records. My main concern is fig ...

What is the best way to show an error message in AngularJS if passwords do not match?

I recently started learning Angularjs and I'm struggling with displaying an error message when the password doesn't match the confirm password. Can anyone provide some guidance? I'm still new to programming so any help is appreciated. Thank ...

Using the section :export in the SCSS :root declaration

In the file test.module.scss, I store all my variables for colors, typography, and more. I want to be able to use these variables in my react components. However, the file starts with :root to define the variables: :root{ --color-white: #fff; --color-b ...

Is it possible to use JavaScript to upload and manipulate multiple HTML files, replacing text within them to create new output HTML pages?

Is it possible to modify the following code to accept multiple files, process them, and then return the output? <html> <head> </head> <body> <div> <label for="text">Choose file</label> <inp ...

How can I activate a jQuery function only when it is within the viewport?

I have installed a jQuery Counter on my website, but I am experiencing an issue where the counter starts or finishes before reaching the section where the HTML code is embedded. Any assistance with this problem would be greatly appreciated! <script& ...

Express.js never terminates a session

I have a Backbone View that makes an Ajax call to the server to delete a session. Upon triggering the following event on the server: app.delete('/session', function(req, res) { if (req.session) { req.session.destroy(function() { ...

Require Google Chrome to show a blank page upon refresh

After reloading the page in either IE/Edge or Chrome/Firefox, I noticed a significant difference. IE/Edge clears the page and displays a white page, while Chrome/Firefox does not. I'm wondering if there is a way to use JavaScript to instruct Chrome/F ...

Loop through an array using a Meteor template

js if (Meteor.isClient) { Template.body.helpers({ fixtures: function () { Meteor.call("checkTwitter", function(error, results) { return results.data.fixtures; }); } }); } if (Meteor.isServer) { Meteor.startup(function ...

The art of properly indenting coffee script code

I encountered an indentation error in these lines Are there any online validators that can assist me? showAliveTests : (pageIndex, statusFilter) -> data= pageIndex:pageIndex status:statusFilter $.ajax u ...

The menu was intended to be hidden when the mouse is moved away, but it actually hides

I'm facing an issue with my button and menu functionality. Even though I have coded the menu to hide itself when the mouse leaves, it hides before the mouse even goes over it. Any suggestions on how to resolve this? function showMenu() { var menu ...

Wait until the npm.load callback is returned before returning module.exports

I am currently facing a situation similar to the one depicted in this simplified example. main.js var settings = require('../settings.js'); console.log(settings.globalData); //undefined The settings.js file relies on an external module (npm) t ...

Why does TypeScript keep throwing the "No inputs were found in the config file" error at me?

Why am I receiving the No inputs were found in config file error from TypeScript? I have set up my tsconfig.json in VS Code, but the error occurs when I try to build it. The terminal displays: error TS18003: No inputs were found in config file '/Use ...

Frequent occurrence of unexpected 'Assertion failed' messages observed on Apple M1 chip

After making the switch from Windows 10 to Mac OS with the latest Apple M1 Silicon, I embarked on my first project on the Mac. I decided to use homebrew to install both node and yarn: brew install node brew install yarn yarn global add @vue/cli My Vue pro ...

Retrieving RadGrid row data by clicking a button within the grid

In the radgrid, there is a column with a button and I need to retrieve the values of the corresponding row when the button is clicked. The row should be identified without actually selecting it. I vaguely remember my friend using ".Parent" or a similar m ...

The PDF document appears quite different from the original HTML page it was created from

Is there a way to create a PDF document that mirrors the appearance of a web page using jsPdf? When attempting this, it seems that the font size, text alignment, and table alignment of the resulting PDF do not match that of the original web page. Additiona ...

Guide on Generating a Response Object in Node.js/Express

My current situation involves needing to execute a res.redirect('/signin'), however, I have already utilized my res object for a res.render. Is there a feasible method for me to create a new Response Object (res) so that I can carry out the redi ...

How can I choose records from collection 'x' in mongodb?

I need to fetch all fields from my database using an API call Here is my code: exports.objfields = async (req, res, next) => { try { var db = mongo.connection; var objeto = req.headers.objeto; const result = db.db.collection(objeto).find( ...

Eliminate any properties with values that exceed the specified number in size

:) I'm trying to create a function that removes properties with values greater than a specified number. I've searched through multiple resources like this question on how to remove properties from a JavaScript object and this one on removing pro ...

What are the methods for distributing a variable in AutoHotkey?

When working in JavaScript, we often utilize the spread operator to spread an array of items, like so: const arr = [1, 2, 3] console.log(...arr) // 1 2 3 Now, in AHK, I am trying to achieve a similar effect: Position := [A_ScreenWidth / 2, A_ScreenHeight ...