How to Check Required Fields on Form Submit
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:
<form>
<div class="ss-item-required">
<label>Question: What is your name?</label>
<input type="text" name="name" id="name" />
</div>
<div class="ss-item-not-required">
<label>Question: What is your email?</label>
<input type="text" name="email" id="email" />
</div>
<div class="ss-item-required">
<label>Question: What is your address?</label>
<textarea name="address" rows="8" cols="75" id="address"></textarea>
</div>
<div class="ss-item-required">
<label>What is your sex?</label>
<input type="radio" name="sex" value="male" />Male <input type="radio" name="sex" value="female" />Female
</div>
<a href="#" onclick="formcheck(); return false">Submit</a>
</form>
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.
function formcheck() {
var fields = $('.ss-item-required').find('select, textarea, input').serializeArray();
$.each(fields, function (i, field) {
if (!field.value) alert(field.name + ' is required');
});
console.log(fields);
}
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.
Amit Agarwal
Google Developer Expert, Google Cloud Champion
Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India.
Amit has developed several popular Google add-ons including Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory