How to Check Required Fields on Form Submit [JavaScript]

Say you have an HTML form contain multiple fields – a mix of textarea, text input, radio button, drop downs (SELECT) and/or check boxes – and some of these fields are required. That is, if the user submits the forms, the browser should display an alert (or an inline message) saying that required fields are missing.

How do you check the submitted form for missing fields? There’s an easy way. Wrap all the required form fields in the HTML with the “ss-item-required” class as show below:

As you can see, the above form has four fields and except for the email address, all fields are required. Next we write a simple JavaScript function that will execute when the user submits the form.

The .serializeArray jQuery function will put all the filled form values into an Array. We are limiting this array to “required” fields only by using the find() function with the item selector.

Next, we iterate through all the fields in the array and if anyone is blank (or has no value), the user is alerted with a message box.

The last console.log will print the content of the form in the Console windows thus making it easy for you to debug input fields. Please note that this only check for missing fields but does not validate the user input.