Prevent Button Click in ASP.NET After Validating Regular Expression in Textbox

How can I ensure that the asp button is disabled only after the user submits the form with the correct regular expression?

Below is the form code:

<asp:TextBox ID="TextBox2" runat="server" placeholder="Email" class="form-control" type="email" Font-Size="Large" oninvalid="setCustomValidity(')"></asp:TextBox>

<asp:Button ID="Button1" runat="server" class="btn btn-primary btn-block btn-lg" Text="Submit" OnClick="Button1_Click" ValidationGroup="S" UseSubmitBehavior="false" OnClientClick="myFunction2()" />

<asp:RegularExpressionValidator ID="RegularExpressionValidator3" ControlToValidate="TextBox2" runat="server" ErrorMessage="Invalid Email" ValidationGroup="S" Visible="false" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>

Here is the validation javascript function:

<script>
    function myFunction2() {
        if (Page_ClientValidate('S')) {
            document.getElementById('Button1').disabled = true;
            document.getElementById('Button1').value = "Please waitً";
         }
 } 
</script>

The issue is that the button gets disabled even when the text box value does not pass the email regex check.

Code Behind:

protected void Button1_Clicked(object sender, EventArgs e)
    {
        System.Threading.Thread.Sleep(5000);
    }

Answer №1

How about we add a touch of client-side JavaScript magic:

var goodEmail = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var goodEntry = /^^(?:(?:[^<>()[\]\\.,;:\s@\"]*(?:\.[^<>()[\]\\.,;:\s@\"]*)*)|(?:\"?.*\"?))@?(?:(?:\[?[0-9]{0,3}\.?[0-9]{0,3}\.?[0-9]{0,3}\.?[0-9]{0,3}\]?)|(?:(?:[a-zA-Z\-0-9]*\.)*[a-zA-Z]{0,}))$/;

$("input")
  .data("oldValue", "")
  .bind("input propertychange", function() {
var $this = $(this);
var newValue = $this.val();

if (!goodEntry.test(newValue))
    return $this.val($this.data("oldValue"));
if (goodEmail .test(newValue)) {
    $this.removeClass("redborder");
    $("#submitBtn").prop("disabled",false);
}
else {
    $this.addClass("redborder");
    $("#submitBtn").prop("disabled",true);
}

return $this.data("oldValue", newValue);
  });

function submitit() {
    console.log($("#email").val() + " is valid and ready to proceed!");
}
.redborder { border: 1px solid red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form>
  <p>Please input your email address:</p>
  <input id='email'>
  <button type='submit' disabled id='submitBtn' onclick="submitit()">Submit</button>
</form>

Despite this, relying solely on client-side validation may not provide enough security. Various vulnerabilities can still arise.

Answer №2

When you need to prevent the submit button from being clicked multiple times during server side processing, you can achieve this by using the OnClientClick attribute of the asp:Button as shown below:

<asp:Button 
  ID="Button1" 
  runat="server" 
  class="btn btn-primary btn-block btn-lg" 
  Text="Submit" 
  OnClick="Button1_Click" 
  UseSubmitBehavior="false" 
  OnClientClick="this.disabled = true; this.value = 'Processing ...';" />

This code will disable the button when it is clicked, and then enable it once the server side operation is complete.

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

Accessing arrays using bracket notation

When working with TypeScript (or JavaScript), you have the option to access object properties using either dot notation or bracket notation: object.property object['property'] Let's explore a scenario using the latter method: const user = ...

I am unable to pass a variable through a callback, and I cannot assign a promise to a

Currently, I am facing a challenge with my code where I need to loop through a hard-coded data set to determine the distance from a user-entered location using Google's web API. The issue lies in passing an ID variable down through the code so that I ...

Utilize NodeJS API to convert a base64 data string into a downloadable PDF file

My NodeJS API is set up to communicate with another API and fetch a data object in the form of a Base64 string. The client making the API call needs to be able to download a PDF file generated from this base64 data. What is the best way to return the dat ...

Enhancing User Experience with JQuery AutoComplete for ASP.NET with Multiple Fields Receiving

I'm currently working on implementing the AutoComplete functionality of JQuery to update multiple fields on an ASP.NET website. While I've successfully managed to get a single textbox to work, I'm struggling with updating multiple textboxes ...

Discover the power of combining app.use and app.get in Node.js for enhanced functionality

I am working on a React application that is rendered by my Node server. I would like to not only render my React app but also call my server as an API to receive some data. How can I achieve this? Below is a snippet from my Node server: .... app.use(&a ...

Creating a custom dialog box using JavaScript

How can I create a customized dialog box in the center without displaying "the host name says..." using CSS? function myFunction() { alert("Record Save"); } Thank you in advance! ...

Adding hue to the portion of text following a JavaScript split() operation

I need assistance in printing the text entered in a textarea with different colors. I am separating the string using the split() method, which works fine. However, I now want to print the substrings in the textarea with colors. How can this be achieved? & ...

What is preventing me from inheriting from the abstract class System.Enum?

According to MSDN, System.Enum is described as an abstract class: [SerializableAttribute] [ComVisibleAttribute(true)] public abstract class Enum : ValueType, IComparable, IFormattable, IConvertible MSDN also states the purpose of an abstract class in the ...

Verify whether an image is present without actually displaying it

I am currently integrating a script for hover-functionality: function VerifyImage(url) { var httpRequest = new XMLHttpRequest(); httpRequest.open('HEAD', url, false); httpRequest.send(); return httpRequest.status != 404; } The c ...

Is it feasible to save BoxGeometries or MeshLambertMaterial in an array using Three.js?

var taCubeGeometryArray = new Array(); var taCubeMaterialArray = new Array(); taCubeGeometryArray.push(new THREE.BoxGeometry( .5, .5, .5)); taCubeMaterialArray.push(new THREE.MeshLambertMaterial({map: THREE.ImageUtils.loadTexture( "image.png" )})); Could ...

Tips for loading and updating data simultaneously in VUEJS from a single input

Currently, the data is displayed in a span tag with an input for updating it Is it possible to fetch data from an API, load it into an input field, update the input with new information, and send it back? What are the best approaches for achieving this? ...

Remove the "x" character from the phone field if an extension is not provided in the Jquery masked input plugin

Currently utilizing the jquery Masked input plugin. The mask I have applied to a field is as follows: "?999-999-9999 x9999" Why is there a ? at the beginning? This was implemented to prevent the field from clearing out when an incomplete number is ente ...

The ng-repeat function is iterating through the array multiple times

Using ng-repeat to bind the same array multiple times. JavaScript : $scope.currentitem = item; $scope.currentitemCategory = $scope.currentitem.category.split(','); console.log($scope.currentitemCategory); HTML: <div ng-repea ...

Why is the leading zero being ignored when I try to print the contents of the session in PHP?

Encountering an issue with printing the content session. The problem arises when creating the session, as the variable is initially in string format (varchar obtained from a mysql field): Initial variable: 09680040 Printed with alert or displayed in div: ...

Parsing a JSON array containing objects with numerical keys in ASP.NET - A step-by-step guide

I've been working on an ASP.NET project and I’m dealing with a JSON array sent from the client in this specific format: [ {"1": "value1"}, {"5": "value2"}, {"10": "value32"} ] My goa ...

Error Found in Angular2 Console Inspection

So, when I check the webpage inspection console, I see this error: Uncaught SyntaxError: Unexpected token { at Object.<anonymous> (main.bundle.js:3885) at __webpack_require__ (polyfills.bundle.js:51) at eval (eval at <anonymous> (m ...

Is there a risk of overloading the server and browser by making constant AJAX calls at regular intervals?

I am in the process of creating a website that requires notifications. I want to use AJAX to continuously check for updates in my database where notifications are stored at regular intervals. My concern is, with multiple users all accessing the AJAX call ...

"Optimizing the placement of a range slider for pricing options

As a beginner in HTML, CSS and JS, I recently faced the challenge of creating a price slider range on a website. However, I am struggling with repositioning it. After copying the code from this link, I noticed that the slider is positioned at the top of th ...

The Express Generator is having trouble detecting the routes within the users file when using app.use('/login', users)

Having used the express generator, I am facing confusion regarding why I cannot utilize the users.js routes file for my login routes. I have created the POST route below, and when I keep it in app.js, everything works smoothly. However, if I attempt to mo ...

Using the outer ng-repeat's object property to filter nested ng-repeat items

I'm currently working on nesting two ng-repeats with two separate JSON files. The goal is to filter the second ng-repeat based on parameters from the first ng-repeat. The first JSON file, $scope.matches, includes information about each match in the W ...