开发者

Using javascript and php together

开发者 https://www.devze.com 2022-12-31 15:22 出处:网络
I have a PHP form that needs some very simple validation on submit. I\'d rather do the validation client-side, as there\'s quite a bit of server-side validation that happens to deal with writing form

I have a PHP form that needs some very simple validation on submit. I'd rather do the validation client-side, as there's quite a bit of server-side validation that happens to deal with writing form values to a database. So I just want to call a javascript function onsubmit to compare values in two password fields. This is what I've got:

function validate(form){
  var password = form.password.value;
  var password2 = form.password2.value;
  alert("password:"+password+" password2:" + password2);

  if (password != password2) {
    alert("not equal");
    document.getElementByID("passwordError").style.display="inline";
    return false;
  }
  alert("equal");
  return true;
}

The idea being that a default-hidden div containing an error message would be displayed if the two passwords don't match. The alerts are just to display the values of password and password2, and then again to indicate whether they match or not (will not be used in production code).

I'm using an input type=submit button, and calling the function in the form tag:

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" onsubmit="return validate(this);">

Everything is alerting as expected when entering non-matching values. I would have hoped (and assumed, based on past use) that if the function returned false, the actual submit would not occur. And yet, it is. I'm testing by entering non-matching values in the password fields, and the alerts clearly show me the values and the not equal result, but the actual form action is still occurring and it's trying to write to my database.

I'm pretty new at PHP; is th开发者_如何学运维ere something about it that will not let me combine with javascript this way? Would it be better to use an input type=button and include submit() in the function itself if it returns true?


If an error in JavaScript occurs, the return false is not reached and the form will be submitted anyway.

And there is an error in your javascript: getElementByID should be getElementById.


use a javascript library like prototype and a method like Event.stop() :

http://www.prototypejs.org/api/event/stop


Make sure the method actually returns false. If there is an error before the return false statement, such as on this line

 document.getElementByID("passwordError").style.display="inline";

then the form may still submit.

0

精彩评论

暂无评论...
验证码 换一张
取 消