Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

form validation with javascript to php

I find this code in W3Schools. It's about form validation with Javascript.

When the user tape wrong mail format, an alert is appear.

When I check the code I see on form onsubmit="return validateForm();, well the function return false in error case.

So my question is how to get the boolean value from javascript to use it in PHP to write error message instead of use of message box.

This is my code:

<html>
<head>
    <script type="text/javascript">
    function validateForm()
    {
    var x=document.forms["myForm"]["email"].value
    var atpos=x.indexOf("@");
    var dotpos=x.lastIndexOf(".");
    if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
      {
      alert("Not a valid e-mail address");
      return false;
      }
    }
    </script>
    </head>

    <body>
    <form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">
    Email: <input type="text" name="email">
    <input type="submit" value="Submit">
    </form>
</body>

</html>

Thanks in advance.

Ali

like image 985
Ali Ben Messaoud Avatar asked Jun 29 '11 19:06

Ali Ben Messaoud


2 Answers

You can't get the boolean value from javascript. What you need to do is have an error div ready in advance. Something like this:

<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<div id="error"></div>
<input type="submit" value="Submit">
</form>

Add css to it to hide it. Then in your validation form, use javascript to alter the HTML of the error div.

  if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
  {
      document.getElementById("error").innerHTML="Not a valid e-mail address";
      return false;
  }

The "return false;" part is to tell the form not to submit. As mentioned in other answers PHP and Javascript do not interface. PHP is server side, Javascript is client side. They don't talk to each other. They can, however, both modify the HTML. Just remember, Javascript always runs in the browser. So if it needs to send things to PHP you need to use AJAX to call a server side PHP script and send the information that way. Most of the time, however, when you are using Javascript, it isn't PHP that needs the information, it's the user. So using Javascript to modify the HTML does the trick.

like image 53
Daniel Bingham Avatar answered Oct 14 '22 09:10

Daniel Bingham


if (..)
{
   document.getElementByID('error').InnerHTML = "Not a valid e-mail address!";
   return false;
}
else
{
   document.getElementByID('error').InnerHTML = "";
}

and in your markup add:

<span id="error"></span>
like image 32
MRR0GERS Avatar answered Oct 14 '22 07:10

MRR0GERS