tags:

views:

105

answers:

2

Javascript needed to prevent form submit if any of field is empty. all my form fields start names start with name=add[FieldName] those are the fields that need checking.

PHP, backend check before submiting to database double check to make sure all $POST are not empty

A: 

I'm not going to write the javascript, but here's some PHP.

$valid = true;
foreach($_POST as $key)
{
    if(!isset($key))
    {
        $valid = false;
    }
}

if(!$valid)
{
    header("Location: /path/to/form");
}
Josh K
You meant to use `isset` not `unset`.
LeguRi
Also, `$key` would be better named `$value`; to save time, why not just `header(Location:...)` and `exit` or `die` as soon as `$ valid` becomes false?
LeguRi
thanks for the code Josh. Sorry for requesting code, I know it wasn't really a question. Stackoverflow seems to be the best place for fast and reliable help. this is the final code I used. <code> foreach($_POST['add'] as $value) { if(isset($value)) { $valid = false; $err .= 'please fill in all fields'; $en['reg_error'] = '<div class=err style="color: #FF0000;"><b>'._error.': '.$err.'</b></div><br>'; load_template('modules/members/templates/reg_gender.tpl'); } } <code>
acctman
@Richard: Nice spot, yes I did.
Josh K
+1  A: 

Here's a javascript function you can use. Just call it for each id belonging to the fields in question.

function isEmpty(field_id) {
  var empty = false;
  if (document.getElementById(field_id).value == null)
    empty = true;

  if (document.getElementById(field_id).value == "")
    empty = true;

  return empty;
}

If you have them predictably named, you could call this function in a loop. If, for instance, they were named field1, field2, ..., field23, then you could just have the following in your main code body:

for (i = 0; i < 24; i++) {
    var emptyCheck = false;
    if(isEmpty("field"+i)) {
        emptyCheck = true;
        //do whatever you want to do when a value is empty
    }
}
JGB146
hi jgb146 is there a way to do it for all id fields, so there's not a long list of coding. i have about 23 fields
acctman
I'll edit my response to include some possible code for this.
JGB146