When the textbox fails validation, it should display an error message within the same textbox and prevent the user from proceeding to another textbox

Here is a JavaScript function and a textbox in the code snippet below. The validations work perfectly. The goal is to clear the textbox value and keep the cursor in the same textbox if the validation fails, without moving to other controls.

JS:

function CheckValidity(txtInput, REGEXP) {
    var mySplitResult = new Array();
    mySplitResult = REGEXP.split("~~");

    var iReturn = 0;
    for (i = 0; i < mySplitResult.length - 1; i++) {

        var re = new RegExp(mySplitResult[i]);
        if (!txtInput.match(re)) {
            iReturn = iReturn + 1;
        }
    }

    if (iReturn > 0) {
        alert("Failed...");
    } else {
        alert("Success...");
    }

}

Codebehind:

 txtField.Attributes.Add("onblur", "javascript:CheckValidity(document.getElementById('" + txtField.ClientID + "').value, '" + hidRegExp.Value + "');");

Answer №1

I can't figure out why this isn't working for me. I tried creating a simple example with just 2 textboxes.

<form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtField" runat="server"></asp:TextBox>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    </div>
</form>

Here is the script I'm using:

<script type="text/javascript">
    function validate() {
        var txt = document.getElementById("txtField");
        if (txt.value === "" || txt.value.length <= 1) {
            txt.value = ''; // to clear the textbox value
            txt.focus(); // focus on the textbox
        }
    }
</script>

This code is in the aspx.cs file:

protected void Page_Load(object sender, EventArgs e)
{
  txtField.Attributes.Add("onblur", "javascript:validate()");
}

Answer №2

When triggering the Leave event or the blur event for any control, it is possible to invoke the validate() function. This function targets any invalid input and keeps the focus on the textbox until valid data is entered.

http://jqueryvalidation.org/validate/

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

Create a bookmarklet for Webdriver when initializing the driver, or store the bookmarklet in your saved bookmarks, all done without the need to

Need Help Adding Custom Bookmarklet to Webdriver I am looking for a way to include a custom bookmarklet (a bookmark that consists of pure JavaScript code) in a webdriver so it appears on the bookmarks toolbar. I would like to achieve this either during th ...

Parse an xslx document and translate it into a List data structure

I'm dealing with an xslx file that contains the following data: www.url.com www.url.com www.url.com www.url.com www.url.com www.url.com www.url.com www.url.com ... As you can see, only one column is being used wit ...

Using jQuery and PHP to send a dynamic form through AJAX

I'm currently working on a pet registration form where users can add new pets. When a user clicks the "add pet" button, I use jQuery to clone the pet section of the form and give each cloned section an id like #pet-2, #pet-3, and so on. Although my ...

The IsKey property is not included in the return value of GetSchemaTable()

-Hello, everyone!- In the midst of developing a C# with ASP.NET project, I've encountered a challenge. The goal of the project is to dynamically load metadata and records from tables in order to edit them without specifying statically which tables ca ...

Accessing the Bootstrap tab form from an external source

I currently have Bootstrap tabs on a page and they are functioning correctly. However, I am looking to open these tabs from an external page. Is this feasible? <div role="tabpanel"> <ul class="nav nav-tabs" role="tablist"> ...

Exploring the ins and outs of console interactions in JavaScript

I have come across a problem on Hacker Rank that seems quite simple. The task involves working with N strings, each of which has a length no more than 20 characters. Additionally, there are Q queries where you are provided a string and asked to determine ...

Checking React props using Jest and Enzyme - A simple guide

Trying to understand React testing, I came across two files: Button.js and Button.test.js The code below contains the question along with comments: // Button.js import React from 'react'; import { string, bool, func } from 'prop-types&apos ...

Tips for passing navigator reference to React Native's <Drawer/> component?

Utilizing react-native-drawer ( https://github.com/root-two/react-native-drawer ) in my index.ios.js file, I have the following setup where I am attempting to pass the 'navigator' reference into the <DrawerPanel /> of <Drawer /> compo ...

What are the steps for creating a new npm package based on an existing one?

I'm a newcomer to the node ecosystem and the npm package system. In my redux/react web app, I currently make use of the photoswipe package alongside react-photoswipe. Recently, I decided to extend the functionality of the photoswipe package by making ...

Encountering difficulties while attempting to delete with a router.delete command - receiving a 404 not

Within my application, I am passing the request parameter 'id' in the router.delete method and communicating it with the Vuex service. However, when triggering the action, an API call is made but it results in a 404 error indicating "not found" a ...

How can jQuery be used to target a specific class based on its inner value?

For instance, within a div of the same class, there are 6 "p" tags - some containing 'member' text and others not. I aim to use jQuery to select all "p" tags with 'member' as their inner text and apply an additional class to them. Here ...

The Evolution of Bulma's Navigation Menu

Creating a transparent menu in Bulma has been successful for the desktop viewport: VIEW DESKTOP MENU However, when attempting to implement the same design on mobile, the menu ends up like this: VIEW MOBILE/TABLET MENU The mobile version seems to inheri ...

Sending a post request in AngularJS using the $resource API

As a beginner in angularjs, I am working on creating a login form that connects to a REST API URL when the user submits the form. http://XXX/XXX/index.php/report/login/format/json Using PostMan REST client to configure the URL works fine! However, when ...

Have you not heard of the greatness of Selenium before?

I've been trying to automate the process of selecting my shoe size, adding it to the cart, and checking out whenever I visit a sneaker page like FootLocker or FootAction. However, each time I attempt to run the script, I encounter the following error: ...

Rotate Chevron icon downwards on mobile devices in a Multilevel Dropdown Bootstrap 4

Bootstrap 4 is being utilized for my current project, I am looking to modify the rotation of the chevron icon in a multi-level dropdown menu specifically on mobile devices when the parent link is tapped, Here is the code snippet for the multi-level dropd ...

Transfer the address information to the billing address fields

I need assistance with copying the user's address to the billing address fields based on a checkbox value. Currently, when the checkbox is checked, only the last input field value is being copied over to the billing address section. It is crucial that ...

Utilizing JQuery to extract element tags exclusively, without including their interior content

I am trying to work with a string that includes HTML and I need to remove the span element entirely while preserving its contents within the string (specifically, I want to retain the word "Canadian" and any other elements). var htmlString = <p>Th ...

Find the current elapsed time using Wavesurfer in real time

I am currently utilizing the waveSurfer library created by katspaugh for playing audio files. In order to display 'elapsed time / total time', I have written code in the following manner: waveSurfer.on('play', function() { $scope.g ...

Is there an efficient method for matching "data-" attributes with property names in mixed case?

In my custom jQuery plugins, I utilize a base plugin class that goes beyond what the jQuery UI widget offers by handling more complex tasks. Currently, I am looking to extract values from data- attributes attached to elements and incorporate them as optio ...