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

jQuery modal window extension

Currently, I am utilizing a jQuery popup plugin that opens a popup window using the anchor's href. For example: <a href="/some/site?hello=hi" class="popup">link</a> There could be an unlimited number of these on my page, each pointing to ...

Is it possible to apply CSS to only the first element?

I have designed a pricing form like the one shown below: To view a full page version of my code for easier reading, please click on the link provided. @import url('http://fonts.googleapis.com/css?family=Indie+Flower'); @import url('http: ...

Is it possible to define the sequence of wrapped items in CSS flexbox?

I am using a <div> with CSS flex to maintain responsiveness. I want to control the order in which elements are wrapped. For instance, I need 1 - 2 - 3 To be rearranged as 1 3 2 Once fully wrapped. Here is my current code: https://jsfiddle.net/ ...

I'm having trouble getting the code to work properly after the "else" statement using both jQuery and Javascript. My head is

Being a newcomer to javascript and jquery, debugging and viewing log files seem like a challenge compared to php. Any help from experienced individuals would be greatly appreciated. Although my code mostly works fine, I'm having trouble with the if/e ...

Determine if an object is already present in a JSON array by comparing their respective IDs

I have a shopping cart stored in JSON format. [{"tuote":{"id":"2","name":"Rengas 2","count":16,"price":"120.00"}},{"tuote":{"id":"1","name":"Rengas 6","count":"4","price":"25.00"}},{"tuote":{"id":"4","name":"Rengas 4","count":"4","price":"85.00"}}] Form ...

Modifying the color of Bootstrap icons

When I use PHP code to print this icon into a table, it looks like this: echo '<button Onclick="" style="border: none; background: none; color:green"><a title="Reenviar" data-toggle="tooltip"><i class="material-icons">&#xE0BE;&l ...

Generate table rows by automatically summing the rows and column data using a loop

I'm currently working on a form that dynamically adds data to columns and rows. While I've successfully generated the column names based on database data and used a loop to add details, adding rows has proved to be quite challenging :) Is ther ...

Finding and removing an element using Jquery

$.ajax({ type: "GET", url: "ajax/getLinks.php?url=" + thisArticleUrl }).done(function (data) { var extractedContent = $(data).find("#content > div > div.entry.clearfix"); extractedContent.find("#content > di ...

Chart: Observing the Discrepancy in the Initial X-Axis Points

I'm working on incorporating multiple charts onto one page, with each chart centered and stacked one after the other. I've set a fixed width for the graph canvas. The challenge arises from the varying ranges of tick values - one chart may have a ...

Broken links detected in the Full Page Navigation menu on a one-page website

The hyperlinks on this particular page seem to be malfunctioning despite the fact that the li.a tags are correctly targeting specific section IDs. Markup: <header> <a href="#0" class="nav_icon"><i></i></a> </header> ...

Is there a way to restrict a user to selecting just one checkbox in a bootstrap checkbox group?

I am having trouble implementing bootstrap checkboxes in my code. I want the user to be able to select only one checkbox at a time, with the others becoming unchecked automatically. Can someone please advise me on what I need to add to my code? Here is a ...

A simple way to add a value from a select option into a textarea when there are several dropdown menus and select elements sharing the same

I have several divs with the same class names where I need to input a value from a dropdown menu into the textarea that belongs to the div where the select element is located. I want this function to work smoothly even with more than 10 divs, which is why ...

My website's links are fully functional with Mozilla Firefox, providing a seamless browsing experience for users

When accessing my website using Google Chrome, Safari, and Internet Explorer from different computers in various locations, I noticed that certain links do not work properly. Surprisingly, these links function perfectly when using Firefox. For instance, o ...

"Customize the appearance of ng-bootstrap datepicker selection with a unique

Having trouble with the ng-bootstrap datepicker when selecting style for month and year. https://i.sstatic.net/grlK6.png The issue seems to be with the select style. select[_ngcontent-c21] { -ms-flex: 1 1 auto; flex: 1 1 auto; padding: 0 .5re ...

What is the best way to transfer information from a client's HTML to a node.js server?

I needed to transmit JSON data to a node.js server. Here is my server.js code: var http = require('http'); var util = require('util') http.createServer(function (req, res) { console.log('Request received: '); util.log(util. ...

Encountering an AJAX issue while attempting to retrieve data

I've encountered a persistent issue with errors in my ajax call from jQuery, specifically within the index.php program. Even after attempting to simplify the problem, I am still facing the same error. Below is the code snippet from index.php: <scr ...

Steps for converting SCSS to CSS using node-sass

I have a main.scss file with numerous imports from other .scss files. Whenever I make changes to any of the *.scss files, the master.css file is automatically generated. I rely solely on NPM for my build process and do not use Gulp or Grunt! It's imp ...

Struggling to access a .html page using Selenium?

Currently utilizing behat/mink, selenium 2 driver, and chrome driver in php to navigate a unique issue. Attempting to access a dummy HTML page proving challenging. Our team is implementing a chatbot onto our main site's landing page as an iframe posit ...

How can I create eye-catching animations for Android applications?

Looking to enhance my Android skills by incorporating animations and games into my projects. How can I achieve this and are there any helpful tutorials available? Is it feasible to use jQuery for creating animations within an application? Primarily inter ...

Removal based on specific conditions upon losing focus

Here is the HTML code snippet that I am working with: <input type="text" id="myText"> <div id="myDiv"> I want to achieve a specific functionality where, when the user focuses out of the text field, #myDiv should be removed only if the user ha ...