How to change the color of error message in jquery validation in JavaScript?


Let's learn how to modify the colour of the error message in JavaScript while using jQuery form validation in this tutorial. Form validation is the process of verifying the pertinent data that the user has submitted in the input field. Here, we'll demonstrate how to use jQuery to validate a straightforward form with a login, password, and confirmed password.

Necessary requirements − The fundamentals of HTML, CSS, JavaScript, and jQuery must be familiar to you.

Method

  • To start, you must create an index.html file that contains an HTML form containing input fields for the user name, email address, password, and confirm password. The form controls in Bootstrap will be used with Bootstrap 4. Add the "myApp.js" file, which contains jQuery code for form validation, after the closing "<body>" element.

  • To validate the entire form, create a myApp.js file using the code provided below.

  • Hiding all error messages in the myApp.js file after the document is finished. Carry out the job of validating each input field, including the username, email, password, and confirm password.

index.html file − The form design for user input is shown in the following HTML code below.

<!DOCTYPE html>
<html>
<title>How to change the color of error message in jquery validation in JavaScript - TutorialsPoint</title>
<head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   
   <!-- Latest compiled and minified CSS -->
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
  
  <!-- jQuery library -->
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
   <!-- Popper JS -->
   <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
   
   <!-- Latest compiled JavaScript -->
   <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</head>
<body><br>
   <h1 class="text-center text-success">
      Welcome to TutorialsPoint!
   </h1>
   <h5 class="text-center">
      JQUERY FORM VALIDATION ERROR MESSAGE DISPLAYS RED COLOR
   </h5><br>
   <div class="container">
      <div class="col-lg-8 m-auto d-block">
         <form>
            <div class="form-group">
               <label for="userN">
                  Username:
               </label>
               <input type="text" name="username" id="myuserName" class="form-control">
               <h5 id="verifyUser" style="color: red;">
                  Please enter the Username
               </h5>
            </div>
            <div class="form-group">
               <label for="userE">
                  Email:
               </label>
               <input type="email" name="email" id="email" required class="form-control">
               <small id="emailvalid" class="form-text text-muted invalid-feedback">
                  Please enter your valid email id
               </small>
            </div>
            <div class="form-group">
               <label for="password">
                  Password:
               </label>
               <input type="password" name="pass" id="password" class="form-control">
               <h5 id="checkPassword" style="color: red;">
                  Please enter your password
               </h5>
            </div>
            <div class="form-group">
               <label for="confirmPass">
                  Confirm Password:
               </label>
               <input type="password" name="username" id="confirmPass" class="form-control">
               <h5 id="checkConfirmPass" style="color: red;">
                  Please enter your correct password
               </h5>
            </div>
            <input type="submit" id="submitbtn" value="Submit" class="btn btn-success">
         </form>
      </div>
   </div>
   
   <!-- Including myApp.js jQuery Script -->
   <script src="myApp.js"></script>
</body>
</html>

myApp.js file − In the HTML file above, the validation is executed using the jQuery code below.

// Document is ready
$(document).ready(function () {
   // Validate Username
   $("#verifyUser").hide();
   let usernameError = true;
   $("#myuserName").keyup(function () {
      validateUsername();
   });
   function validateUsername() {
      let usernameValue = $("#myuserName").val();
      if (usernameValue.length == "") {
         $("#verifyUser").show();
         usernameError = false;
         return false;
      } else if (usernameValue.length < 4 || usernameValue.length > 12) {
         $("#verifyUser").show();
         $("#verifyUser").html("The length of the username should be between 4 and 12 characters.");
         usernameError = false;
         return false;
      } else {
         $("#verifyUser").hide();
      }
   }
   
   // Validate Email
   const email = document.getElementById("email");
   email.addEventListener("blur", () => {
      let regex = /^([_\-\.0-9a-zA-Z]+)@([_\-\.0-9a-zA-Z]+)\.([a-zA-Z]){2,7}$/;
      let s = email.value;
      if (regex.test(s)) {
      email.classList.remove("is-invalid");
      emailError = true;
      } else {
         email.classList.add("is-invalid");
         emailError = false;
      }
   });
   // Validate Password
   $("#checkPassword").hide();
   let passwordError = true;
   $("#password").keyup(function () {
      validatePassword();
   });
   function validatePassword() {
      let passwordValue = $("#password").val();
      if (passwordValue.length == "") {
         $("#checkPassword").show();
         passwordError = false;
         return false;
      }
      if (passwordValue.length < 4 || passwordValue.length > 12) {
         $("#checkPassword").show();
         $("#checkPassword").html(
         "The length of the password should be between 4 and 12 characters."
         );
         $("#checkPassword").css("color", "red");
         passwordError = false;
         return false;
      } else {
         $("#checkPassword").hide();
      }
   }
   
   // Validate Confirm Password
   $("#checkConfirmPass").hide();
   let confirmPasswordError = true;
   $("#confirmPass").keyup(function () {
      validateConfirmPassword();
   });
   function validateConfirmPassword() {
      let confirmPasswordValue = $("#confirmPass").val();
      let passwordValue = $("#password").val();
      if (passwordValue != confirmPasswordValue) {
         $("#checkConfirmPass").show();
         $("#checkConfirmPass").html("Please enter your correct password");
         $("#checkConfirmPass").css("color", "red");
         confirmPasswordError = false;
         return false;
      } else {
         $("#checkConfirmPass").hide();
      }
   }
   // Submit button
   $("#submitbtn").click(function () {
      validateUsername();
      validatePassword();
      validateConfirmPassword();
      validateEmail();
      if (
      usernameError == true &&
      passwordError == true &&
      confirmPasswordError == true &&
      emailError == true
      ) {
      return true;
      } else {
         return false;
      }
   });
});

Output

The above code will give the below output −

The result produced whenever a user directly clicks the submit button is shown below.


The output that results from a user entering inaccurate information into the form is seen below.


In the below example let us understand how to display errors in JavaScript without an alert box. JavaScript errors could be shown without alert boxes, however using an alert box is the more common practice. Without the use of an alert box, errors can be displayed using the way below.

Method

Making use of the textContent property. To put it simply, textContent is used to dynamically update any node's content. Developers could use this property to show any content and attract users' attention in a manner similar to alert boxes.

Syntax

node.textContent = "Some error message"

// To draw attention
node.style.color = "red";

Example

<!DOCTYPE html>
<html>
<title>How to change the color of error message in jquery validation in JavaScript - TutorialsPoint
</title>
<head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   
   <!-- Latest compiled and minified CSS -->
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
   <!-- Latest compiled JavaScript -->
   <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
   <style>
      h1 {
         color: rgb(16, 125, 187);
      }
      .container {
         padding: 15px;
         width: 420px;
      }
      label,
      input {
         margin-bottom: 20px;
      }
      button {
         float: left;
         margin-left: 20px;
         background-color: rgb(42, 152, 158);
         color: #fff;
         cursor: pointer;
      }
   </style>
</head>
<body style="text-align:center">
   <h1>Visit TutorialsPoint to learn JavaScript</h1>
   <b>You will notice the error will be dislplayed in red color</b>
   <br><br>
   <div class="container">
      <div>
         <label>Enter Your Name:</label>
         <input type="text" size="50">
      </div>
      <div>
         <label>Enter Your Phone No:</label>
         <input type="text" id="myNumber" size="50">
         <span id="showError"></span>
      </div>
      <button type="submit" onclick="errorMessg()">
         Submit
      </button>
   </div>
</body>
<script>
   function errorMessg() {
      let showError = document.getElementById("showError")
      if (isNaN(document.getElementById("myNumber").value)) {
         
         // switching content and color of content
         showError.textContent = "The entered Phone No is not valid"
         showError.style.color = "red"
      } else {
         showError.textContent = "We will contact you shortly"
         showError.style.color = "green"
      }
   }
</script>
</html>

Entering characters instead of number you will get the error message.

After entering the phone number you will get a success message instead of the error message.

Updated on: 09-Dec-2022

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements