I am trying to verify my code, but the messages are not displaying under the username. They only appear under the password field. I am not sure where I have made a mistake

Having trouble with my login form validation using jQuery. Can someone help me fix it?

$(document).ready(function() {
  $("#form1").validate({
    rules: {
      username: {
        required: true,
        minlength: 6
      },
      password: {
        required: true,
        minlength: 5

      }
    },
    messages: {
      username: {
        required: "Username is mandatory"
      }
    }
  });
});
.error {
  color: red;
}

p {
  font-size: 13px;
  font-style: arial;
  font-align: left;
}

body {
  font-family: calibri, arial, sans-serif;
  background-color: powderblue;
  margin: 0;
  padding: 0;
  border: 0;
  outline: 0;
}

span.password {
  float: right;
  padding-top: 50px;
}

.login-form {
  margin-top: 5%;
  margin-bottom: 5%;
  position: relative;
  width: 390px;
  left: 35%;
  height: 500px;
  border: 6px solid#ff0000;
  padding: 10px;
  background-color: #00ffff;
}

.login-form h1 {
  font-size: 50px;
  text-align: center;
  text-transform: uppercase;
  margin: 40px;
}

.login-form label {
  font-size: 29px;
  text-align: right margin:45px;
}

.login-form input[type=text],
.login-form input[type=password] {
  font-size: 20px;
  width: 350px;
  padding: 10px;
  border: 0;
  outline: none;
  border-radius: 5px;
}

.login-form button {
  font-size: 16px;
  color: white;
  background-color: green;
  font-weight: bold;
  padding: 79px;
  width: 60%;
  margin: 10px 15px;
  padding: 8px 6px;
  border: 5px;
  cursor: pointer;
}

.login-form button:hover {
  border: solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="jquery-validation/dist/jquery.validate.min.js">
</script>
<script src="js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>

<div class="login-form">
  <h1>LOGIN PAGE</h1>
  <form action="#" name="form1" id="form1">

    <label for="firstname">First Name</label>
    <input type="text" name="firstname" id="firstname" placeholder="username"><br>
    <br>
    <label for="password">Password</label>
    <input type="password" name="password" id="password" placeholder="pswd"><br>

    <input name="submit" type="submit" id="submit" class="submit" value="Submit">
    <span>
        <input type="checkbox"  id= "remember" name="remember " value="remember me"> 
        <label for ="checkbox" name="checkbox" >Remember me</label>
        </span>
    <span class="password">Forget <a href="#" >Password ?</a></span>
  </form>
</div>

Answer №1

To cater to your specific situation, you can utilize HTML5 validation attributes for validation.

The provided HTML snippet demonstrates the use of required, minlength, pattern, and max validation attributes.

<form action="#" id="formOne" novalidate>
        <div class="FormGroup">
            <label for="name">Name</label>
            <input 
                type="text" 
                class="FormGroup__Input"
                name="username"
                placeholder="username"
                data-v-input  
                minlength="6" 
                required
            />
            <span class="FormGroup__ErrorLabel"></span>
        </div>
        <div class="FormGroup">
            <label for="password">Password</label>
            <input 
                type="number" 
                name="password"
                class="FormGroup__Input"
                placeholder="password"
                data-v-input
                minlength="5"
                required
            />
            <span class="FormGroup__ErrorLabel"></span>
        </div>
        <button type="submit">Submit</button>
</form>

Instructions to set up this form:

  1. Add the novalidate attribute on the form element to validate inputs using javascript code.
  2. Ensure each input element has a unique name attribute.
  3. Incorporate the data-v-input attribute to identify input elements for Javascript validation.
  4. Specify HTML5 validation rules for each input element.
  5. To display errors, add an element directly below the respective input element. NOTE: The error label must be the next sibling of the input field.
'use strict';
const formNode = document.querySelector("#formOne");

initValidation(formNode, (form, data) => {
    alert(JSON.stringify(data, null, 4))
});

function initValidation(formNode, onSubmitHandler){
    const validationErrors = [];
    const inputs = formNode.querySelectorAll("[data-v-input]");
    const selects = formNode.querySelectorAll("[data-v-select]");

    formNode.addEventListener("submit", handleSubmit);
    inputs.forEach(input => input.addEventListener("blur", handleBlur));
    inputs.forEach(input => input.addEventListener("input", handleInput));

    function handleSubmit(evt){
        evt.preventDefault();
        let formData = {};

        if(inputs.length > 0){
            inputs.forEach(input => {
                validateInput(input);
                formData[input.name] = input.value;
            });
        }
        if(selects.length > 0){
            selects.forEach(select => {
                validateInput(select);
                formData[select.name] = select.value;
            });
        }
        if(validationErrors.length === 0){
            formNode.reset();
            onSubmitHandler(formNode, formData);
        }
    }

    function handleBlur(evt){
        validateInput(evt.target);
    }

    function handleInput(evt){
        validateInput(evt.target);
    }

    function validateInput(inputNode){
        if(inputNode.validity.valid){
            let inputNodeIndex = validationErrors.indexOf(inputNode.name);
            validationErrors.splice(inputNode, 1);
            renderErrorLabel(inputNode, false);
        } else {
            validationErrors.push(inputNode.name);
            renderErrorLabel(inputNode);
        }
    }

    function renderErrorLabel(node, show = true){
        node.nextElementSibling.textContent = show ? node.validationMessage : "";
    }

    return true;
}
  1. Copy the initValidation function into your javascript file.

To begin validating your form, call the initValidation function after the DOM is loaded. It requires two arguments.

  1. a form node: obtained through document.getElementById or any DOM selectors. However, only one form node should be passed to initValidation.
  2. a callback that receives the form node as its first argument and the form's data as the second argument. Place any post-validation actions in the body of this callback. NOTE: This callback is triggered only when all validations pass without errors.

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

Duplicate text content from a mirrored textarea and save to clipboard

I came across some code snippets here that are perfect for a tool I'm currently developing. The codes help in copying the value of the previous textarea to the clipboard, but it doesn't work as expected when dealing with cloned textareas. Any sug ...

Creating an HTML structure that limits each li to only contain three div elements can be achieved using React and Underscore.js

To achieve this specific layout, I am looking to utilize only underscore.js functions. Below is the array that I have: var xyz = [{ 'name': 'test' },{ 'name': 'test1' },{ 'name': &ap ...

"Disappearing act: Navigating through pages causes the navigation

Struggling with navigation in my asp.net core web app development. My directory structure includes the use of Areas. When navigating through pages in the main folder like Index, Index1, and Private, everything works fine. However, once I navigate to an Ar ...

Troubleshooting a problem with dynamic options in Materialize select set

I'm currently facing an issue with my two dependent dropdowns, country and state. When I select a country, I use JavaScript to populate the respective states in the state dropdown. However, even though the options are added correctly when I inspect th ...

Make Fomantic-UI (Angular-JS) sidebar scroll independently

Is there a way to make a sidebar scroll independently of the content it pushes? Currently, my page is structured like this: -------------------------- |[button] Header | -------------------------- |S | Main content | |i | ...

Press here to expose the remaining portion of the text using the truncate helper

Has anyone tried using jQuery with the truncate helper method in Rails? I've managed to turn the omission symbol into a link_to like this: <%= raw(truncate(@book.description, :length => 1000, :omission => (link_to' (continued)', :i ...

Enhance Your Tables with JQuery Calculations

I have a table that is populated from a database. Each field in the table is hidden until it is selected from a dropdown list. I also need to calculate the total of only the visible rows, not all rows including hidden ones. Can you please advise on how I c ...

Eliminate distinct objects during touchend event in a multi-touch web application

Despite my best efforts and endless searching online, I am struggling to find a solution. While the touchstart and touchmove events allow me to retrieve a unique id from touches.identifier, it seems impossible to achieve this with the touchend event. M ...

Resizing nested elements while maintaining consistent padding dimensions

If you're looking to create a sleek foundation for a 200px wide, 30px high editable combobox that can be easily used with angular binding or other JavaScript data-binding solutions, consider the following HTML code. However, there's a desire to m ...

In JavaScript, provide a boolean response to a callback function from a separate function

Working with the jQuery validate plugin involves utilizing a submitHandler callback function. This function determines whether the form submission should proceed based on its return value - false will prevent submission, while true will allow it to go thro ...

Create a button that matches the dimensions of the background image

I am working with a form that includes a submit button featuring a background image. <button type="button" class="button" alt="Send" onclick="validate_form_newsletter_wide( form )"></button> Everything works well when I define the dimensions ...

How to set DIVS to be hidden when the page first loads

I am currently working on a project where I need to use JavaScript to hide certain <div> elements when the page loads. I have also included jQuery in my code. Below is what I have tried so far: $(document).ready(function() { hide(); function hid ...

Looking to incorporate nested rules in `JSS` using `CSS`?

Can someone guide me on how to use CSS class-nesting in Material-UI or JSS in general? I have been attempting the following: card: { cardHeader:{ marginTop:"30px" } } ...

Easily generate a hierarchical layout in HTML with this straightforward method

I'm currently working on implementing a hierarchical tree structure for a website. I need to organize a user's projects, tasks, and sub-tasks in a visually appealing manner using HTML elements. Any suggestions or creative ideas are welcome! ...

Utilize Z-index to hide elements from view

Encountering an issue with hiding other div elements when one is visible. In the code snippet below, I aim to make Pacific Rim and World War Z disappear using z-index when Star Trek is visible. Here's my HTML code: <!doctype html> <html ...

enable jQuery timer to persist even after page refresh

code: <div class="readTiming"> <time>00:00:00</time><br/> </div> <input type="hidden" name="readTime" id="readTime"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script&g ...

Is there a way to control the visibility of two divs depending on which one a user hovers on?

Having two stacked div elements containing images, I want the div with id = "features3_HDS_image" to become visible when a user hovers over the div with id = "HDS_Blurb", and the div with id = "features3_FH_image" to be displayed when hovering over the div ...

Ensuring form accuracy upon submission in AngularJS 1.5: Understanding the $invalid state in relation to $pristine field

When loading data in a form, I want to allow the user to submit data only if the form is valid. Initially, the form is pristine but invalid. If the user edits any one of the three fields, the form is no longer pristine, which is acceptable. However, the ...

What's the best way to utilize a navigation bar across various pages?

I have just completed designing my home/index.html page. I want to ensure that the navigation bar remains in place and visible as users navigate through all of my pages. Do I need to manually copy and paste the navigation code into the top of each page? Or ...

Performing an AJAX post request in PHP is resulting in an unexpected HTML comment being returned, which ultimately

I am encountering an issue with my index.html file that is making an AJAX request to a PHP page for JSON data. The code seems to be functioning properly, but occasionally the PHP file returns '' before the actual JSON text. The problematic retur ...