开发者

PHP and Javascript code needed to check if form fields are not empty

开发者 https://www.devze.com 2022-12-26 02:58 出处:网络
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.

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 $PO开发者_开发百科ST are not empty


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
    }
}


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");
}
0

精彩评论

暂无评论...
验证码 换一张
取 消