Function To Show Error Message Using jQuery

Hi, today in this article I am going to show you how we can create a common js function to show the validation error message at bottom of the input field. This article will help beginners who are just starting their career in IT Field or just started learning code.

Validation are like,

  • has the user filled in all required fields?
  • has the user entered a valid date?
  • has the user entered text in a numeric field?
  • has the user entered correct mobile number?
  • has the user entered right range?
  • has the user entered correct email address?

In this article I am going to create one HTML form using HTML and CSS then I will show using jquery function how we can show the error message at bottom of the input field on the submit button click.

Step 1

Create a HTML form index.html using below code,

<div class="container brahmaprakash">
<h1>
Simple Form using HTML and CSS.
</h1>
  <form action="brahma">
    <div class="row">
      <div class="col-25">
        <label for="firstName">First Name</label>
      </div>
      <div class="col-75">
        <input type="text" id="firstName" name="firstname" placeholder="Your name..">
      </div>
    </div>
    <div class="row">
      <div class="col-25">
        <label for="lastName">Last Name</label>
      </div>
      <div class="col-75">
        <input type="text" id="lastName" name="lastname" placeholder="Your last name..">
      </div>
    </div>
    <div class="row">
      <div class="col-25">
        <label for="country">Country</label>
      </div>
      <div class="col-75">
        <select id="countryName" name="countryName">
          <option value="australia">India</option>
          <option value="canada">Ireland</option>
          <option value="usa">England</option>
        </select>
      </div>
    </div>
    <div class="row">
      <div class="col-25">
        <label for="subject">Message</label>
      </div>
      <div class="col-75">
        <textarea id="Message" name="message" placeholder="Please enter subject name" style="height:200px"></textarea>
      </div>
    </div>
    <div class="row">
      <button id="submit"> Submit</button>
    </div>
  </form>
</div>

Step 2

Now create the CSS file as Index.css and paste the below code.

input[type=text], select, textarea{
  width: 100%;
  padding: 10px;
  border: 2px solid #ccc;
  border-radius: 5px;
  box-sizing: border-box;
  resize: vertical;
}

label {
  padding: 10px 10px 10px 0;
  display: inline-block;
}

#submit {
  background-color: #04AA6D;
  color: white;
  padding: 11px 19px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  float: right;
}

.container {
  border-radius: 4px;
  background-color: #f2f2f2;
  padding: 22px;
}

.col-25 {
  float: left;
  width: 25%;
  margin-top: 6px;
}

.col-75 {
  float: left;
  width: 75%;
  margin-top: 6px;
}

.row:after {
  content: "";
  display: table;
  clear: both;
}

@media screen and (max-width: 600px) {
  .col-25, .col-75, input[type=submit] {
    width: 100%;
    margin-top: 0;
  }
}

Step 3

Now you can add the js file as index.js and use the below code.

validateFormValues = () => {
    let firstName = $("#firstName").val();
    let lastName = $("#lastName").val();
    let countryName = $("#countryName").val();
    let subject = $("#Message").val();
    let firstNameValueValid = 0;
    let lastNameValueValid = 0;
    let countryNameValueValid = 0;
    let subjectValueValid = 0;
    if (firstName != null && firstName != "") {
        firstNameValueValid = 1;
        $("#firstNamewrongValue").remove();
    } else {
        firstNameValueValid = 0;
        dispalyErrorMessage("#firstNamewrongValue", "#firstName", "First Name Required.");
    }
    if (lastName != null && lastName != "") {
        lastNameValueValid = 1;
        $("#lastNamewrongValue").remove();
    } else {
        lastNameValueValid = 0;
        dispalyErrorMessage("#lastNamewrongValue", "#lastName", "Last Name Required.");
    }
    if (countryName != null && countryName != "") {
        countryNameValueValid = 1;
        $("#CountryNamewrongValue").remove();
    } else {
        countryNameValueValid = 0;
        dispalyErrorMessage("#CountryNamewrongValue", "#countryName", "Country Name Required.");
    }
    if (subject != null && subject != "") {
        subjectValueValid = 1;
        $("#subjectNamewrongValue").remove();
    } else {
        subjectValueValid = 0;
        dispalyErrorMessage("#subjectNamewrongValue", "#Message", "subject Required.");
    }
    if (firstNameValueValid == 0 || lastNameValueValid == 0 || countryNameValueValid == 0 || subjectValueValid == 0) {
        return false;
    } else {
        return true;
    }
};
dispalyErrorMessage = (errorMessageId, inputFieldId, errorMessage) => {
    $(errorMessageId).remove();
    var errorMessageNewId = errorMessageId.split("#");
    $(inputFieldId).parent().after("<span id='" + errorMessageNewId[1] + "'>" + errorMessage + "</span>");
    $(errorMessageId).css("display", "block");
    $(errorMessageId).css("width", "100%");
    $(errorMessageId).css("color", "red");
    $(errorMessageId).css('required', true);
    $(errorMessageId).css('margin-top', "-15px");
    $(errorMessageId).css('margin-bottom', "10px");
};
$('#submit').unbind('click');
$('#submit').click(async (ele) => {
            let validate = validateFormValues();
            if (validate) {
                //do your code for validate values.
            }
        };

It will help your form validation.

Thanks.