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条)

报告相同问题?

悬赏问题

  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝