How to add validations to an html form or Inputs using jQuery in 2022 | jQuery Form Validation Methods with Repo link!

Karan Kaul | カラン
6 min readFeb 27, 2022

--

This is a short article on “how to add validations to an HTML form using jquery”. I will be using jQuery in this post to demonstrate how you can validate your form data before it is submitted. I will also write a separate post for doing form validations with vanilla JavaScript and link it at the end of this article when it's ready. Link to the github repo is at the end of the post.

How to validate a form when it is submitted / at time of submission (button type = submit)

This is where I will show you how to check form inputs & validate them before the form is submitted to the server.

Firstly, here is what I have for the html form —

html form validations using jquery
html form for validation (code)
html form validations using jquery
what it looks like on the frontend

I assume you have already included the jQuery CDN links at the top of your file.

Now, I am adding an onClick event on the submit button. We can validate what we want inside the callback of this onClick function and return True or False. The form won’t submit or proceed to its action if our function returns False in any case. Otherwise it will continue submission.

So, we will perform the checks inside this function and then return true / false accordingly.

validation function jquery
onclick function (validation.js file I created)

What is important to understand here is that our form will submit or go to the action URL only when our callback returns True or nothing. To stop it from proceeding, we must strictly return False. Now let me begin by adding some checks for our username field.

Username input length validation —

validate username jquery
only submit form if username is 4 or more chars long

The condition checks if the length of the username entered by user is less than 4 or not. If it is then it returns false and the form isn’t submitted. Otherwise it is submitted without any problem.

Email containing ‘@’ symbol & dot(.)com at the end —

validate email in jquery
checking for dot(.)com & ‘@’ symbol in validation

The condition above checks if there is an ‘@’ in the email & “.com” at the end. I basically said, if email includes @ and .com is at the end (by subtracting its index from length of email, we should get 4 as .com is 4 chars long), then I negated (NOT) the whole thing by adding “!” at the front which means the conditions are not met and hence we return False in this case.

Phone Number being 10 digits long—

validate phone number jquery
phone number length validation

This is a basic check for a phone number. We simply return false if it isn’t 10 digits long. I have not added a check to see if user has entered inputs other than digits in this field, but that can also be checked easily or you can just use a number input field on the form.

If you would like to add a check then you can do a check like the one I have written below. parseInt(x) will return only integers from the input and hence it won’t match x if there were characters in it as well.

if (parseInt(x) != x) → return False ;

Now, combining every check, we have this —

jquery validation checks
combined form validations

Now our form will only submit if and only if —

  • Username is 4 or more characters long.
  • Email contains “@” symbol and “.com” is at the end.
  • Phone number contains 10 digits.

I think at this point, it must be quite clear to you how we can do validations and how easy they are to implement. But there is still something missing from this tutorial. . .

That’s right! We have not given the user any feedbacks or prompts to let them know that their data is invalid. For that I will add some extra code in our html file and also our JS file. Lets go!

Sending visual feedback / messages to notify the user that their data is invalid

For adding messages on the page, I will add new <spans> next to each input. Whenever there is an invalid data, we will write a message in the span next to that input to let them know the data is invalid. We don’t want duplicate messages to appear so we will firstly clear this span each time the user hits submit.

show message on screen jquery
added spans for error messages after validation

I will update our old JS code & remove multiple return statements as they will actually stop our code from executing further down. We want to check all validations & also show messages on their corresponding span tags, all at once.

If we keep the returns where there are now, it will only add one span message at a time because it will keep returning false and our function won’t get executed completely.

Instead of retuning false multiple times, I will use a flag variable or status variable. This var will tell me at the end of the function, whether we should return true or false. We will change the value of this var based on checks and at the end, based on the value of this var, we will return false or true only a single time.

show message on screen jquery validations
setting isValid false based on conditions

Now our function doesn’t stop execution in between. It simply sets the variable isValid to false if any of the conditions don’t pass the checks.

Now we can add the feedback message to notify the user.

adding messages to show on the frontend

We had 3 different spans with classes “user-error”, “email-error” & “phone-error”. I have appended another span tag inside those tags based on our conditions.

i.e this line —

$(‘.user-error’).append(“<span class=’msg py-2 fw-bold text-danger’>Minimum 3 characters are required.</span>”)

will simply append a span with class msg inside a span we already had with the class of “user-error”.

Now it should work ok, we can see this on the frontend —

jquery validation frontend view
validation messages are added on the page

There is still an issue. Remember I told you we will remove old spans each time the user submits the form. Our code currently will append new spans without deleting the previous ones. Like so —

duplicate messages on screen - jquery validation
duplicate messages adding up

We obviously don’t want that, so let’s just remove older messages each time user submits. I will call the .remove() on “.msg” class. This is the class I gave to each message span tag. NOTE — This is the actual message tag we are adding with jQuery, not the outer one.

jquery form validation 2022 with example
final code after removing older messages

And this is the final output we have —

Final output after validations in jquery

Okay. That is all for this tutorial. I hope you are able to understand everything I have written, with ease. If you find it confusing or difficult then just know that it takes a while before it starts to make sense.

It is not difficult, maybe my language actually confused you. But it is not difficult, you will get the hang of it pretty quickly if you keep practicing even just a little bit.

You can find the code for this tutorial here.

Thankyou for reading. Good luck!

~Karan Kaul | カラン

--

--

Karan Kaul | カラン

Writes about Programming & Technology (mainly Machine Learning) Connect with me on Linkedin - https://www.linkedin.com/in/krnk97/