Annoying blank space triggered by custom jQuery validation error labels

I'm facing an issue with jQuery validation custom error placement. When adding a label with the custom error, it creates unwanted white space at the bottom of each input/select field.

Custom Error Label in jQuery:

<label for="autocomplete" class="text-left p-0 m-0 error text-danger" generated="true"></label>

https://i.sstatic.net/UpbxN.jpg

To remove the white space, I used the following CSS:

label.error {
   display: none!important;
}

However, this solution causes the custom errors not to appear during form validation.

Is there a way to have the custom jQuery errors shown only when they are validated, perhaps by setting display:none as default?

DEMO FIDDLE

I'm open to any CSS3 or JQuery hacks that can help resolve this issue. I've been struggling with this problem for the past few days.

Thank you!

jQuery

jQuery.validator.addMethod('lettersonly', function(value, element) {
    return this.optional(element) || /^[a-z," " áãâäàéêëèíîïìóõôöòúûüùçñ]+$/i.test(value);
}, "Please enter letters and spaces only");

$(".signupForm1").validate ({
errorPlacement: function(error, element) {
    return false;
}, 

rules: {
    autocomplete:{
        required: true,
        minlength: 3,
        maxlength: 30,
        lettersonly: true
    },

    state:{
        required: true
    },

    email2: {email:true, required:true}
},

messages: {
    email2: {
        required: "Please enter your email address"
    },   
    state: {
        required: "Please enter your state"
    },
    autocomplete: {
        required: "Please enter your city",
        minlength: "City name too short",
        maxlength: "City name too long",
        lettersonly: "Only use letters and spaces"
    }
}

});

HTML

<form id="signupform" class="mt-4 p-sm-3 p-2 signupForm1 input-group mb-sm-3 rounded" method="post" action="#">

    <div class=" form-row w-100">

    <div class="input-group col-sm-8 col-12 w-100 ">
       <label style="" class=" w-100">
      <input type="text" name="autocomplete" id="autocomplete" class="lightfield form-control sentence rounded" placeholder="City"/> <div style=""class="ml-1">  <label for="autocomplete" class="text-left p-0 m-0 error text-danger" generated="true"></label>      </div>

     </label>
    </div>



           <div class="input-group w-100 col-sm-4 col-12 px-1"> 
            <label class=" w-100">

      <select id="inputState" name="state" class="state lightfield form-control sentence rounded">
        <option value="" selected>State</option>
        <option value="AK">Alaska</option>
        <option value="AL">Alabama</option>
        <option value="AR">Arkansas</option>
      </select>

<div style=""class="ml-1">  <label for="inputState" class="text-left p-0 m-0 error text-danger" generated="true"></label>      </div>

     </label>
    </div>

               <div class="input-group w-100 px-1"> 
            <label class=" w-100">
                <label for="email2" class="sr-only">Enter your email address</label>
                <input style ="" id="email2" type="email" name="email2" class="rounded anchor sentence form-control" aria-label="Large" placeholder="Email Address"/>        
                <div style="" class="ml-1">  <label for="email2" class="p-0 m-0 error text-danger" generated="true"></label>  
                </div>
        </label>

<button style="" id="enter" name="signup" type="submit" class="bg-success rounded text-uppercase font-weight-bold w-100 mb-2 ctabutton sentence text-white btn btn-secondary btn-lg">Sign up</button>   

       </div>

          </div>

        </form>

Answer №1

I'm not entirely clear on the question and can't guarantee this solution will work, but it's worth a try.

You could experiment with adding an invalidHandler to the validate function that changes the display property to block, then set the default to none. Here is an example:

label.error {
   display: none;
}
$(".signupForm1").validate ({
errorPlacement: function(error, element) {
    return false;
}, 
invalidHandler: function(event, validator) {
    $(document).find('label.error').css('display', 'block !important');
},
  ...
});

Hopefully this suggestion proves useful.

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

IDs are an effective way to differentiate between classes within a program

I am facing an issue with displaying user info only when hovering over a specific image. The appearance of the hover effect is correct, but I'm struggling to show the info on just the hovered image. Any suggestions on how to achieve this? To see a l ...

jQuery $.ajax problem encountered

When working with AngularJS, we have the ability to catch errors using the $http() service as shown below: return $http(defaultConfig).then(sendResponseData)**.catch(errorCallBack)**; On the other hand, when attempting to do something similar in jQuery: ...

What could be causing the CSRF Token mismatch error to occur solely on the initial page load following my login within my Laravel 8 application?

One issue I'm encountering is with a form that relies on an AJAX call to load values into certain fields once the first input is filled. In my blade file, I have included the CSRF token as an input using "@csrf". However, when making the AJAX call, I ...

I implemented the order property in the css, however the layout positions remain unchanged

<section id="home"> <div class="container"> <div class="row align-items-center container-items"> <div class="col-md-6"> <div class="info"> <h1>Lorem ...

Navigation bar not adjusting to the size of the mobile device's screen

My website can be found at . I'm trying to make my navbar mobile-friendly and usable on all devices. However, when I tested it on my iPhone, the navbar appears extremely tiny. Please inspect the code using dev tools to see what I mean. Below is the co ...

Using JQuery to switch out images that do not have an ID or class assigned

Currently, I am using a Google Chrome Extension to apply an external theme to a website. Unfortunately, the logo on the site does not have an ID or class that can be used to call it. I am searching for a solution to replace it with a different image. My ...

Intercepts clicks outside of element borders when heading has a line-height lower than 1

Right after an anchor tag, I have an H1 element. The line-height of the H1 element is set to '0.9' for design purposes. As a result, the computed height of the H1 becomes shorter, but the actual Text element inside overflows and covers part of t ...

having difficulty configuring gwt-button's corners to be rounded

Hey there, I'm having an issue with a button in my GUI that I created using GWT. I'm trying to round the corners of the button, but using border-radius doesn't seem to have any effect on its appearance. The style sheet I'm using is "co ...

Utilizing /deep/ and the triple greater than symbol (>>>) within Angular 2

After researching the /deep/ and ::shadow selectors, I've come across conflicting information. In a discussion on Stack Overflow: What do /deep/ and ::shadow mean in a CSS selector? It was noted that Chrome has deprecated the /deep/ combinator and i ...

From Table to DIV: A Simple Conversion

I have encountered a major issue that has stumped me so far. Perhaps you can assist me. I am dealing with a table that appears as follows: __________________________________ | | time1 | time2 | time3 | +--------+-------+-------+-------+ | John | ...

Use jQuery to incorporate the loaded file into the DOM

I have successfully loaded a file into a div element. $("#div").load("file.txt"); The file contains HTML images. I am trying to target them using $('#div>img') or other selectors, but it doesn't seem to be working. If the images were ...

Tips for designing posts within a Bootstrap card column

I have a code snippet for displaying posts in a bootstrap card column layout. %h4{:align => "center"} All Posts %hr.my-3 - @posts.each do |post| %h4= link_to post.title, post %p= post.description %p= post.company I am looking to display the firs ...

ACF Repeater not displaying correctly within ACF Gallery

I am currently in the process of incorporating ACF fields into my Owl Carousel. Although I have successfully managed to display the images, there is a problem where all the results from its repeater are being outputted into each slide at once, rather than ...

Adjust Fancybox Dimensions Dynamically with Form Submission and AJAX

I am working on a form with the following code: <form action="getData.php" method="POST" id="myForm"> <input type="input" size="20" name="myName" /> <input type="submit" value="Login" id="submit" /> </form> This form passes the da ...

Why does my window scroll change when making a $.ajax call?

Encountering a peculiar bug... Whenever my JS code enters the success function after a jQuery $.ajax call, the scroll position on my window suddenly jumps to the bottom of the page. This is problematic for me as I'm developing a mobile page and want t ...

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 ...

Unable to create a clickable image

My approach involves using asp:Hyperlink controls to create an image that acts as a link. Here is the sample code in both aspx and C#: <asp:HyperLink ID="mainInteractiveFileLink" runat="server"> </asp:HyperLink> C# mainInteractiveFileLink ...

The error handler in AngularJS $http service is always left wanting for a call

Here's the code snippet I'm currently using: $http .post('/api/login', $scope.user) .success(function (data, status, headers, config) { // code }) .error(function (data, status, headers, config) { // code }); It seems to be functi ...

Looking for ways to include CSS links in Sublime Text 2 program?

Currently, I am diving into the world of Sublime Text 2 and I must say, I am quite impressed with its capabilities. However, there are a few features that I miss from my previous editor (Microsoft Expression Web). One particular functionality I found extr ...

The functionality of Bootstrap's push and pull options appears to be malfunctioning

Exploring the grid option pull and push has presented some challenges for me. I suspect the issue lies in my implementation of bootstrap CSS and/or JS (not certain if push/pull are controlled by JS or CSS). I've included a push-pull setup at the top ...