What is the best way to alter the CSS Class of a textbox when validation fails and then revert it back when validation is successful?

I am working on a registration page that is styled with bootstrap. The form validation is done using

<asp:RequiredFieldValidator>
and
<asp:RegularExpressionValidator>
.

My goal now is to change the style of the form elements when validation fails, and revert back to the original style when validation is successful.

I have come across suggestions like adding an error class using

txtBox.CssClass += "error_class";
, but I am looking for a more precise solution. I came across a script that changes the CSS on failed validation, but it does not reset to the original CSS upon successful validation.

The original CSS class of the textbox is: form-control

What would be the easiest way to achieve this, like setting the border-color to red...??

P.S.: In the bootstrap template I am using, there are two fields: id and class. Here:

class: form-control

id: inputError

Current method to change class:

<script type="text/javascript">
        function BtnClick() {
            var val = Page_ClientValidate();

            if (!val) {
                var i = 0;
                for (; i < Page_Validators.length; i++) {
                    if (!Page_Validators[i].isvalid) {
                        $("#" + Page_Validators[i].controltovalidate).css("border-color", "red");
                    }
                }
            }
            return val;
        }
    </script>

Answer №1

Consider incorporating additional conditionals to account for the inverse scenario. It may also be beneficial to establish a secondary class specifically tailored for handling invalid inputs.

<script type="text/javascript>
    function BtnClick() {
        var val = Page_ClientValidate();

        if (!val) {
            for (i = 0; i < Page_Validators.length; i++) {
                if (!Page_Validators[i].isvalid) {
                    if (!($("#" + Page_Validators[i].controltovalidate).hasClass("form-invalid")))
                        $("#" + Page_Validators[i].controltovalidate).toggleClass("form-control form-invalid");
                }
                else {
                    if (!($("#" + Page_Validators[i].controltovalidate).hasClass("form-control")))
                        $("#" + Page_Validators[i].controltovalidate).toggleClass("form-control form-invalid");
                }
            }
        }
        return val;
    }
</script>

Utilize form-control as your standard class and form-invalid as the class responsible for applying a red border.

For further information, refer to this link: removeClass() if it exists, and this link: jquery change class name if you wish to modify the method in any way.

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

Page for Calling with jQuery Mobile

How can I navigate to the administrator page while also refreshing the page? The concept is: If the user logs in successfully, the page will automatically redirect to the administrator page using HTML5 storage for data. For example: sessionStorage.setIte ...

The event activates the method, but no changes are made to the page

I am facing an issue with multiple listboxes within an update panel. The OnselectedIndexChanged event of the first listbox triggers a method that should update the subsequent listboxes. However, currently, only the first listbox is updating the second one ...

Adding a class in JavaScript as an element scrolls

I am trying to implement a script that adds the class navbar-fixed-top to the navigation when the user scrolls. Here is the code I have so far: var nav; function yScroll(){ nav = document.getElementById('nav'); yPos = window.pageYOffset; ...

Gather image origins from a website, even if img tags are inserted through javascript or other methods during the page's rendering

I am looking to extract the URLs of all the images from a web page using C# and asp.net. Currently, I am utilizing: WebClient client = new WebClient(); string mainSource = client.DownloadString(URL); Afterwards, I am scanning the mainSource string for i ...

Tips for creating an indent in a new line

https://i.stack.imgur.com/O8Xbv.png I've been trying to figure out how to make the text indent on each new line when it's pushed to a new line due to screen resizing. I've tried using 'display:block' but it doesn't seem to wo ...

Cease the endless scrolling on the resizable iframe

Currently, I am developing a website that incorporates another webpage from a distinct domain within an iframe. The page's content perfectly fits the iframe, thus preventing any overflow or scrollbars. Nevertheless, users can zoom in on the content us ...

Issues detected with Foundation Block Grid in small size setting

I created a React component to display a series of div elements on a page using the Foundation Block Grid system to control the number of divs per row. However, I am facing an issue where the number of divs does not change when switching to a small-sized s ...

The process of overriding CSS applied through JavaScript

I am using a third-party multi-select dropdown. Similar to Select2, the multi-select dropdown is created using JQuery with select2.min.js and the width of the dropdown is automatically calculated. Is there any way to apply static width to it, as I believe ...

Having Trouble Choosing Options From Dropdown Menu Using Index in Selenium with Java

I am familiar with how to choose an element from a dropdown using the selectByIndex method. However, when attempting to use selectByIndex (select.selectByIndex(index)) on the HTML snippet below: <select id="destinationAllocationId" name="destinationAll ...

Leveraging the power of Required (html5) feature in Internet Explorer

What should I do if I want to make a textbox required on my webpage, but the issue is that it uses an HTML5 attribute? Is there a solution or alternative available? This is how I create my TextBox: @Html.TextBoxFor(model => model.SubChoiceText, new { ...

Unusual CSS media queries behavior

During my project work, I faced a puzzling issue which can be illustrated with the following example: Here is the sample CSS code: *, *::after, *::before { box-sizing: border-box; margin: 0; border: 0; } @media only screen and (max-width ...

Flex sliding side bar with UI router

I'm working on implementing a sliding side-bar feature, but I've run into an issue where the main view snaps into place while the side bar slides in. To better illustrate this problem, I've set up a demonstration on Plunkr. The body doesn&ap ...

Ensure that Roboto font is utilized on IE 11 and Edge browsers

My goal is to implement the Google Roboto font in my project, but I'm noticing that it doesn't display properly in IE11 / Edge browsers. Below is a snippet of my code: <!DOCTYPE html> <html> <head lang="en"> <meta charse ...

Using jQuery to target a specific item from a retrieved list of elements

I'm currently working on a photo gallery feature that is reminiscent of Instagram or Facebook user photos. My goal is to enable users to view details about each image (such as the date) in a box that appears over the image when they hover over it. E ...

MaskedEditExtender does not retain the mask after clicking elsewhere

I'm having trouble understanding why the MaskedEditExtender for my Phone Number field isn't retained after clicking away, while the rest are functioning properly. I've checked the properties and controls and they all seem to be identical. I ...

How to make sure a bootstrap row fills the rest of the page without exceeding the height of the screen

In my Angular application, I am using bootstrap to create the following structure (simplified version). <div class="container"> <div class="header> <div class="mat-card> <!-- Header content --> < ...

Unable to get 'margin: 0 auto' to function properly on mobile devices

We recently created a website at but are facing issues with mobile device compatibility and centering the content using margin: 0 auto along with a specified width. The problem can be seen here: for "topuctovnici.sk" We have set .core to 1240px in widt ...

Separating the rules for development and production modes in the webpack configuration file

I'm currently in the process of working on a front-end project using HTML. Within my project, I have integrated the Webpack module bundler and am utilizing the image-webpack-loader package for image optimization. However, I've encountered an issu ...

Create a dynamic and adaptable Google Maps experience without the need for an iframe

For instance, if you are using an embedded Google Map. You can ensure that your Google Map is responsive with the following code: Using iframe (simple iframe) <div class="ggmap"> <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m ...

Error message: validator is not defined when integrating jquery.validate with jquery.uploadfile package

Currently, I am facing an issue while attempting to incorporate both jquery.validate and jquery.uploadfile on the same page. The error message I'm receiving is: TypeError: validator is undefined if ( validator.settings.rules ) { Interestingly, if ...