Prevent submitting empty form

2 posts by 2 authors in: Forums > CMS Builder
Last Post: August 19, 2014   (RSS)

Hey,

There are several ways you can prevent this. The simplest is to add the required attribute to the field, but this is only supported by modern browsers:

http://www.w3schools.com/tags/att_input_required.asp

This will stop the user submitting the form unless they have a value in the field.

Another way is to use jQuery to detect if a user has entered data into the form before it's submitted, this stackoverflow post goes over how you can do that:

http://stackoverflow.com/questions/16556968/jquery-form-submit-to-check-empty-fields

The final method - which you should implement alongside one of the solutions above to ensure the server can only ever return data when a value is entered - , is to use PHP. Here is a simplified example from the Website Membership plugin sign up form:

  // error checking
  $errorsAndAlerts = "";

 // process form
  if (@$_POST['save']) {

    //Check if values have been entered in the fullname and email fields
    if(!@$_REQUEST['fullname'])       { $errorsAndAlerts .= "You must enter your full name!<br/>\n"; }
    if(!@$_REQUEST['email'])          { $errorsAndAlerts .= "You must enter your email!<br/>\n"; }


    // add user
    if (!$errorsAndAlerts) {
      //There are no errors, so carry out an action

    }
  }

So the above code happens when a save variable is present in the form that was submitted. Then we carry out error checking, and add any errors to the errorsAndAlerts variable. If this variable has something in it, then we know there are errors, and not to carry out the action requested in the form. 

Let me know if you have any questions.

Thanks!

Greg

Greg Thomas







PHP Programmer - interactivetools.com