doudeng2016 2014-03-21 19:07
浏览 52
已采纳

仅在输入信息时才进行表单验证

I have some client-side form validation for an email address. Essentially it checks if the email is too short, then if it's too long and finally uses FILTER_VALIDATE_EMAIL to check if it's valid.

However an adjustment has been made to the form. The email field is no longer required. But I don't just want to remove all validation as I still want to ensure that if an email address is input it is correct. It's just not a required field any more.

Here are the nested if statements for the validation at present:

if (isset($_POST['email_address'])){
    $email_address = mysql_real_escape_string(trim($_POST['email_address']));
    $_SESSION['status']['register']['email_address'] = $email_address;
    if(strlen($email_address) > 10){ // email address less than 10
        if(strlen($email_address) < 161){ // if longer than 160
            if(email_valid($email_address) == false){ // email address invalid format
                $_SESSION['status']['register']['error'][] = "The email address has been put in wrong. Please check and try again.";
            }else{ 
                // passed min length, passed max length, passed validation
            }
        }else {
            $_SESSION['status']['register']['error'][] = 'The email address is too long.';
        }
    } else{
        $_SESSION['status']['register']['error'][] = "The email address is too short. It can't be shorter than 10 letters.";
    }
}else{
    $_SESSION['status']['register']['error'][] = "You haven't put in an email address.";
}

But I need to change this to do the following instead, but am having trouble getting my head around the nested statements:

  1. Check IF anything was inputted at all. 2.If it WAS, follow the above.
  2. If it wasn't, progress anyway.

So only if they actually input anything does the validation run. Else it's still OK to go forward with the form check because it wasn't required anyway. The full code can be seen here pastebin.com

  • 写回答

4条回答 默认 最新

  • douyi2107 2014-03-21 19:18
    关注

    change isset to !empty, and remove the else like suggested earlier.

    if(!empty($_POST['email_address']) {
    //do stuff
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改