Client-side validation in Javascript will not function on ASP.Net

I'm facing an issue with validating textboxes in a webform within a Masterpage before saving data to the Database. Strangely, the JavaScript code works fine in a simple Login application but fails in my actual app by saving empty spaces to the database.

Despite trying to debug the code, I can't figure out why it's not working and am at a loss for what else to do.

Below is a snippet of my page code:

    </head>
    <body>
        <form id="form1" class="contact-form text-right">

        <section class="contact-area" id="contact">
            <div class="container-fluid">
                <div class="row align-items-center d-flex justify-content-start">
                    <div class="col-lg-6 col-md-12 contact-left no-padding">
                        <div>
                             <%-- tabla aqui --%>
                            <table style="width: 100%;"</table>
                        </div>
                    </div>
                    <div class="col-lg-4 col-md-12 pt-100 pb-100">

                            <asp:Label runat="server" ID="lblFecha" Text=""></asp:Label>
                            <asp:Label runat="server" ID="lblIDUsuario" visible="false" Text=""></asp:Label>
                            <asp:Label runat="server" ID="lblUsuario" Text=""></asp:Label>


                            <asp:TextBox ID="txtID" visible="true" class="common-input mt-10" type="numeric" readonly="false" runat="server"></asp:TextBox>
                            <asp:TextBox ID="txtTitulo" placeholder="Ingrese el título" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Ingrese el título'" class="common-input mt-10" type="text" runat="server"></asp:TextBox>
                            <textarea id="txtContenido" style="resize:none;" cols="20" rows="5" placeholder="Ingrese el contenido" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Ingrese el contenido'" class="common-input mt-10" type="text" runat="server"></textarea>

                            <asp:Button ID="btnGuardar" OnClientClick="return performCheck();" OnClick="btnGuardar_Click"  runat="server" Text="Guardar" class="primary-btn mt-20"></asp:Button>
                            <asp:Button ID="btnActualizar"  OnClientClick="return performCheck();" onClick="btnActualizar_Click" runat="server" Text="Actualizar" class="primary-btn mt-20"></asp:Button>
                        <asp:Label ID="lblError" runat="server" Text="" ForeColor="Red"></asp:Label>    
                        <div class="alert-msg">
                            </div>

                    </div>
                </div>
            </div>
        </section>
            </form>


        <script type="text/javascript">
            function performCheck() {
                if (document.getElementById("txtTitulo").value == '') {
                    alert(" Debe Ingresar un título");
                    return false;
                }

                if (document.getElementById("txtContenido").value == '') {
                    alert("Debe Ingresar un contenido");
                    return false;
                }

                return true;
            }
        </script>

        <script src="js/vendor/jquery-2.2.4.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
        <script src="js/vendor/bootstrap.min.js"></script>
        <script src="js/owl.carousel.min.js"></script>
        <script src="js/jquery.ajaxchimp.min.js"></script>
        <script src="js/jquery.sticky.js"></script>
        <script src="js/parallax.min.js"></script>
        <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBhOdIF3Y9382fqJYt5I_sswSrEw5eihAA"></script>
        <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
        <script src="js/jquery.magnific-popup.min.js"></script>
        <script src="js/main.js"></script>

    </body>
</html>

This is my custom JavaScript code:

<script type="text/javascript">
    function performCheck() {
        if (document.getElementById("txtTitulo").value == '') {
            alert(" Debe Ingresar un título");
            return false;
        }

        if (document.getElementById("txtContenido").value == '') {
            alert("Debe Ingresar un contenido");
            return false;
        }

        return true;
    }
</script>

Answer №1

Avoid conducting form validations within the on-click handlers of buttons. It is advisable to handle them in the form's submit handler instead. Errors can occur when a user submits a form by pressing Enter in an input field, thus bypassing any validations you may have set up. A helpful example can be found at https://www.w3schools.com/js/js_validation.asp

This case demonstrates why relying solely on client-side validations is inadequate. If ensuring data validity is crucial, it is essential to incorporate server-side validations as well. Users can easily circumvent client-side validations, whether intentionally or unintentionally, so additional measures are necessary.

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

Organize online resources with Configuration Manager/Web Configurations

Recently adopted the Configuration Manager in my asp.net mvc projects to manage connectionStrings for both release and debug modes. Now I'm curious how to achieve the same for a web reference. This is what my current web.config looks like: <appl ...

Obtaining the access token from the URL: A step-by-step guide

Once I have successfully authenticated with Google, the URL I receive is: http://localhost:3000/_oauth/google#access_token=ya29.5HxuYol1Io8JLeGePDznbfkkwu_PC4uodKwG8_1clFYAn9AgdOV1WGpOTNQP3s76HAsn7Y4zWw&token_type=Bearer&expires_in=3600 I am tryi ...

Can a frontend framework be exclusively utilized on a single page within a completed project?

I have a project where I am looking to create a dashboard as the homepage, similar to this example: However, for this project, we are not using any frontend framework, only relying on JavaScript and jQuery. The backend for the project is implemented usi ...

Update the position of a div when an element becomes visible

Currently, I have 3 titles each with a button underneath to reveal more information about the subject. To toggle the visibility of the content, I have implemented a script that shows or hides the corresponding div when the button is clicked. On smaller de ...

In which situations is it required to specify the return type of a function in TypeScript?

When it comes to making functions in typescript, the language can often infer the return type automatically. Take for instance this basic function: function calculateProduct(x: number, y: number) { return x * y; } However, there are scenarios where dec ...

I'm having trouble locating the documents I recently saved in my mongoose model

Here is my current challenge: I am populating a collection called "fruits" with some values. Once the data has been inserted, I want to use map to console.log each fruit individually. However, during the first attempt, instead of displaying a single fruit ...

The React component's state doesn't update when mapping through an array using useState() unless I actively interact with the browser by scrolling or clicking

I’ve successfully implemented a unique effect using React and Tailwind. You can check it out here: Take a look at the GIF showcasing the effect. Everything seems to be working well, except for one issue - the effect only triggers when: I scroll in the ...

Preventing Body Overflow Without Affecting Iframe Overflow in Meteor.js

Currently, I am working on a project using Meteor for a Point of Sale (POS) system. For those unfamiliar with it, Meteor is a framework that allows for the use of JavaScript, jQuery, and various other web app scripting languages. The goal of this applicati ...

One efficient way to handle multiple concurrent tasks in NodeJs is by using the forEach method to iterate

Having trouble getting the promises to return any values, as they are coming back empty. Despite following suggestions on Stack Overflow, I am still unable to resolve this issue. Frustration levels are high and I'm feeling lost; Can anyone help me pi ...

After toggling the class, Jquery will no longer select the button

I am having an issue with my jQuery code where I have a button that, when clicked, should switch classes from #testButton to .first or .second. The image toggle shows that the first click works fine and toggles the image, but the second click does not seem ...

"Utilizing AJAX to fetch and showcase API key along with its corresponding values within an HTML

Seeking assistance with a task. I am currently working on displaying API JSON key and value data in a formatted CSS layout on an HTML webpage. My approach involves making an AJAX call to a Node.js server to retrieve the data. While I have successfully ret ...

Issues encountered when trying to combine ASP.NET Core with Angular 2 using the cli init feature

I am in the process of setting up a new ASP.NET Core project. In the "wwwroot" folder, I executed the command "ng init" via cmd to initialize Angular. After restoring packages, I hosted my ASP project on Kestrel. However, I encountered compile-time errors ...

Deleting JSON files using Discord and Node.js by requiring them from a specific folder

Currently, I am in the process of developing a Discord bot using Node.js. One of the functions within the bot utilizes JSON files to store information about specific entities. I aim to create a command in Discord that, when called with a specific name asso ...

Node Lighthouse is producing discrepancies in its accessibility test results

Something seems off when I compare the scores I get from running LH in the Chrome extension versus running it in node. In Chrome, my page receives a 94 while in node, it gets an 88. I've tried adjusting for desktop vs mobile viewing, but there must be ...

"Transferring a JavaScript variable to Twig: A step-by-step guide for this specific scenario

When it comes to loading a CSS file based on the user's selected theme, I encountered an issue while trying to implement this in my Symfony application using Twig templates. The code worked flawlessly on a simple HTML page, but transferring it to a Tw ...

Leverage the variables' values to access property

There is a way to use this possibility: let eventSelected = "333"; let bestResult = result.personal_records[eventSelected]?.single?.best //like searching like this: result.personal_records.333?.single?.best However, when deali ...

Creating a dynamic image display feature using VueJS

Explore the connections between the elements How can I transmit a value from one child component to another in VueJS? The code snippet below is not generating any errors and the image is not being displayed <img v-bind:src="image_url" /> Code: & ...

how to adjust the width of table columns dynamically using ng-repeat and AngularJS

Working on a user interface that contains a table where the column widths adjust according to percentage data. I'm using ng-repeat to populate the table, but need help setting unique widths for each piece of data received. Here's some of my Angul ...

What are some best practices for managing asynchronous requests on the client side with Node.js?

I am a beginner in NodeJS, currently utilizing it on the server side for my projects. My goal is to create a simple REST-based GET request that takes a search parameter called searchvar from the user and returns any matching records found in a JSON array. ...

Learn the best way to handle special characters like <, >, ", ', and & in Javascript, and successfully transfer escaped data from one text box to another

I am seeking a way to use JavaScript to escape special characters. I came across a code snippet on this URL: http://jsperf.com/encode-html-entities. It successfully handles <>&, but I have encountered an issue with double quotes ("). The JavaScri ...