I have an html form with multiple fields. Some of the fields are required, others are not. I have a JavaScript validation form that will send an alert if a field is empty. However, I only want it to send an alert if a required field is empty. How do I signify which fields in the form should cause the alert message to pop up?


Tom Tolleson

Recommended Answers

All 2 Replies

Member Avatar for langsor

You can test the field by className in your javascript and give all required fields the same class name.

Something like this

var form = document.getElementById('myform');

for ( var i = 0; i < form.length; i ++ ) {
  if ( /required/.test( form[i].className ) {
    if ( !form[i].value ) { // might have to tweek this some ...
      alert( 'You missed a required field: ' + field.name );
      return false; // test failed, abort form submit

// all fields passed the test ...
return true; // or maybe use

What a required field might look like

<input type="text class="required" name="First Name" />

This is off the top of my head, so I don't know it will work "out of the box" but it's the general idea anyway.

Hope this helps

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.