Reputation: 101
Im trying php javascript form validation. There are 2 input fields. And all the 2 fields are manditory. For the first time javascript validation is working and form is not submiting, but when i fill the one text box value of validation error , then the form is submiting without validation.
Here is the html code
<form method="post" name="form_register" id="form_register" action="" onSubmit="return formValidation();">
<input type="text" id="firstname" name="firstname" value="<?=$_POST['firstname']?>" size="25">
<input id="lastname" value="<?=$_POST['lastname']?>" name="lastname" type="text" size="25">
javascript code :
function formValidation()
{
var firstname= document.forms["form_register"]["firstname"].value;
if (firstname===null || firstname==="")
{
alert("First name must be filled out");
document.getElementById('firstname').focus();
return false;
}
var lastname = document.forms["form_register"]["lastname"].value;
if(lastname === null || lastname ==="")
{
alert("Last name must be filled out");
document.getElementById('lastname').focus();
return false;
}
else
{
return true;
}
}
Php code after form submit :
if(isset($_POST['submit']))
{
//insertion goes here
}
For the first time i have not entered in the text fields. result : validation is working.
for the second time submit i have filled only first text box result : form submitted without checking the second input validation
Upvotes: 1
Views: 727
Reputation: 1304
You have a space inside the quotes in your javascript code follow "lastname" on these two lines:
var lastname = document.forms["form_register"]["lastname "].value;
document.getElementById('lastname ').focus();
This could be your problem.
Upvotes: 0
Reputation: 1457
There was an additional space that you have put on the javascript for the name of lastname.
That is you put "lastname " instead of "lastname"
That is what causing the validation (javascript function) to fail after executing that line.
Try this code
<script type="text/javascript">
function formValidation()
{
var firstname= document.forms["form_register"]["firstname"].value;
var lastname = document.forms["form_register"]["lastname"].value;
if (firstname===null || firstname==="")
{
alert("First name must be filled out");
document.getElementById('firstname').focus();
return false;
}
else if(lastname === null || lastname ==="")
{
alert("Last name must be filled out");
document.getElementById('lastname').focus();
return false;
}
else
{
return true;
}
}</script>
<form method="post" name="form_register" id="form_register" action="" onSubmit="return formValidation();">
<input type="text" id="firstname" name="firstname" value="<?=$_POST['firstname']?>" size="25">
<input id="lastname" value="<?=$_POST['lastname']?>" name="lastname" type="text" size="25">
<input type="submit" name="submit" value="submit">
</form>
Upvotes: 2