【问题标题】:How to do both client side and server side validation?如何进行客户端和服务器端验证?
【发布时间】:2020-05-29 17:16:44
【问题描述】:

我正在创建一个 HTML 表单,我在其中进行客户端和服务器端验证。我使用了以下代码。

<form action='logic.php' method='post' id='login'>
    <input type='text' placeholder='Enter name' name='name'>
    <input type='submit'>
</form>

// Jquery
$(document).ready(function(){

    function validate_name(input_id,error_id,msg="Name"){
        const x = document.getElementById(input_id).value;
        const y = document.getElementById(error_id);
        const pattern = /^[a-zA-Z]+$/
        if(x!==""){
            if(pattern.test(x) ){
                if(x.length<3 || x.length>10){
                    y.innerHTML = msg+' should be between 3 and 10 characters.'
                    return false;
                }
                else{
                    y.innerHTML = '';
                    return true;
                }
            }
            else{
                y.innerHTML = 'Should contain only alphabets.'
                return false;
            }
        }
        else{
            y.innerHTML = "Please Enter Your "+msg;
            return false;
        }
    }


    $('#login').submit(function(e){
        e.preventDefault();
        let name = validate_name('rollno','rerror');
        let subject_name = validate_select('subject_dropdown','serror');
        if(name === true & subject_name === true){
            window.location = 'controller/indexPage_logic.php';
        }
    })
});

我可以进行客户端验证,但如果表单得到正确验证,我将无法在服务器端 PHP 中使用 $_POST['name'] 访问输入值。我认为这是由于 window.location .有没有更好的方法来进行双方验证?

【问题讨论】:

  • 如果存在AJAX,为什么要使用window.locationAjax Example SO
  • window.location 执行 GET,您需要发布表单。使用 $.post 并阅读响应

标签: php html jquery


【解决方案1】:

在表单中的操作参数中设置正确的文件。

在 if 条件中,写e.currentTarget.submit();

if(name === true & subject_name === true){
    e.currentTarget.submit();
}

【讨论】:

  • 这行得通。但是如果我检查 isset($_POST['login_submit']) (我的提交按钮的名称)它返回 false。只有输入的值存在于 $_POST 数组中。
  • 设置提交按钮为:
【解决方案2】:

当您需要 POST 时,您的位置更改会执行 GET

改成

$('#login').submit(function(e){
    e.preventDefault();
    let name = validate_name('rollno','rerror');
    let subject_name = validate_select('subject_dropdown','serror');
    if(name === true & subject_name === true){
        $.post('controller/indexPage_logic.php', {name:rollno}, function(response) { console.log(response)}); // do what you need to do when valid on the server too
    }
})

【讨论】:

    【解决方案3】:

    您必须将数据发送到服务器,问题是 window.location 没有向服务器发送任何请求 能够配合使用

    $.post('url to the server', { data1 : "Your data", data2 : yourvar }, function(res) {
       console.log(res)
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-23
      • 1970-01-01
      • 2016-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多