Vijay
Vijay

Reputation: 111

How to do both client side and server side validation?

I was creating a HTML form in which I was doing both client side and server side validation.I used the below code.

<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';
        }
    })
});

I may able to do client side validation but if the form is properly validated I can't able to access the input value using $_POST['name'] in server side PHP.I think this is due to window.location.Is there any better way to do both side validation?

Upvotes: 0

Views: 360

Answers (3)

medmik
medmik

Reputation: 1

You have to send your data to the server, the probleme was window.location didn't sent any request to the server to be able to accomplice that use

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

Upvotes: 0

mustafaj
mustafaj

Reputation: 305

Set the correct file in your action parameter in the form.

And inside the if condition, write e.currentTarget.submit();

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

Upvotes: 1

mplungjan
mplungjan

Reputation: 178109

Your location change does a GET when you need a POST

Change to

$('#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
    }
})

Upvotes: 0

Related Questions