Ivan Pandžić
Ivan Pandžić

Reputation: 373

PHP/JavaScript form validation?

I'm new with PHP and JavaScript. I eant to validate form, and if the form input fields are correct, then send it to php external script. I've tried something like this:

<head>
<script type="text/javascript">
  function Validate(){
    var x=document.forms["form"]["firstname"].value;
    var y=document.forms["form"]["lastname"].value;
    var z=document.forms["form"]["age"].value;
    if(x==null || x=="") {
      alert("Input name!");
    } else if(y==null || y=="") {
      alert("Input surname!");
    } else if(z==null || z=="") {
      alert("Input age!");
    } else {
  // IS IT POSSIBLE TO SEND FORM HERE FORM VARIABLES TO PHP SCRIPT?
    }
  }
</script>
</head>
<body>

  <form name="forma" action="validate.php" method="post" onSubmit="return Validate()">
    Firstname: <input type="text" name="firstname">
    Lastname: <input type="text" name="lastname">
    Age: <input type="text" name="age">
    <input type="submit">
  </form>
</body>
</html>

Upvotes: 2

Views: 5846

Answers (4)

Ihor Patychenko
Ihor Patychenko

Reputation: 196

You need to put this code:

function Validate(){
var x=document.forms["form"]["firstname"].value;
var y=document.forms["form"]["lastname"].value;
var z=document.forms["form"]["age"].value;
if(x==null || x=="") {
  alert("Input name!");
  return false;
} else if(y==null || y=="") {
  alert("Input surname!");
  return false;
} else if(z==null || z=="") {
  alert("Input age!");
  return false;
} else {
  return true;
}
}

Upvotes: 1

michi
michi

Reputation: 6625

You should validate the input server-side (php), even if you did it client-side (javascript).

You do this by checking on $_POST in validate.php:
Quite at the beginning of your script:

if (isset($_POST)) {  // form has been sent

    if (!isset($_POST['firstname']) || strlen($_POST['firstname'])==0) { // no entry 

        $e['firstname']='please enter a firstname!'; // prepare error-msg
    }

    if (!isset($e)) {  // no error, continue handling the data

        // write data to database etc.
    }
}

// in your form...

if (isset($e)) echo "there were errors: ". implode(',',$e);

Upvotes: 1

juco
juco

Reputation: 6342

Your code looks correct, other than the fact you probably want to return false on failure to prevent the form from submitting. When not returning false, the form will simply continue to submit.

I also think you probably meant to name your form form not forma

Upvotes: 1

Captain Payalytic
Captain Payalytic

Reputation: 1071

Since you are not returning false from your function, the form should be being submitted anyway. You can stop it from being submitted by having your validate() function return false.

Upvotes: 1

Related Questions