如何同时进行客户端和服务器端验证?

时间:2020-05-29 08:59:53

标签: php html jquery

我正在创建一个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有没有更好的方法来进行双方验证?

3 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:0)

当您需要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
    }
})

答案 2 :(得分:0)

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

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