简体   繁体   中英

Trying to validate a form client and server side

The client side validation looks something like this:

function validateFname() {
    var x = document.getElementById('fname').value; 
    if (x==null || x=="")
    {
    alert("First name must be filled out");
    return false;
    }
}

The server side below it:

if(isset($_POST['SubmitForm'])){
if(empty($_POST['fname'])){
    echo "First name cannot be empty!<br/><br/>";
    return false;
}

and the form itself below that:

<form name = 'checkout' method='post' action="<?php echo $_SERVER['PHP_SELF']; ?>"
accept-charset='UTF-8'>
First Name:<input type="text" name="fname" id="fname" onsubmit="return validateFname()"
class="required" value="<?php echo $fname;?>" />
<input type="submit" name="SubmitForm" value="Send"/>

Ofcourse there is a lot more to it but ive just given one example above. I am trying to figure out why the (clientside)javascript function is not working and instead the (server) php error is coming up. I need to be able to have the client run validation checks before the server to reduce load.

The onsubmit is a event that belongs to the <form> element. You have placed it with the submit button which won't work.

Here's a working fiddle:

Demo

Reference

<form name = 'checkout' method='post' action="<?php echo $_SERVER['PHP_SELF']; ?>" accept-charset='UTF-8'>
First Name:<input type="text" name="fname" id="fname"  value="<?php echo $fname;?>" />
<input type="submit" name="SubmitForm" onClick="return validateFname()"  value="Send"/>
</form>

try the above code. Instead of using onSubmit in input text field use onClick in submit button. good luck

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM