PHP Validation and Javascript Validation won't work together - javascript

When I combine my php form validation code with my javascript validation code, the javascript code fails to work when I hit the submit button. It will only validate the first form field and not the 3 others and then php will validate all fields. I don't want the php form validation to do anything until javascript has completed the form validation.
When I use only php or only javascript to validate, then the code works correctly. What am I missing here? Is it something to do with the beginning of the form?
"form name="contactform" id="contactform" method="post"
action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"
onsubmit="return validateentry();">"
Am I supposed to do the php form validation while "action" goes to a different web page?
The javascript code:
function validateemail()
{
var emailentry=document.forms.contactform.email.value;
at=emailentry.indexOf("#");
period=emailentry.lastIndexOf(".");
if(at < 1 || ( period - at < 2 ))
{
alert("Please enter correct email in the format of 'yourmail#yourwebsite.com'")
document.forms.contactform.email.focus();
return false;
}
return(true);
}
function validatephonenumber()
{
var re = /(?:\d{3}|\(\d{3}\))([-\/\.])\d{3}\1\d{4}/;
var numbers = document.forms.contactform.phone.value;
var verified = re.exec(numbers);
if (!verified)
{
alert("Please enter a phone number in the format of 999-999-9999");
return false;
}
return(true);
}
function validateentry()
{
if(document.forms.contactform.name.value=="")
{
alert("Please provide your name.");
document.forms.contactform.name.focus();
return false;
}
if(document.forms.contactform.company.value=="")
{
alert("Please provide your company name. If you don't have one, simply state
that you don't.");
document.forms.contactform.company.focus();
return false;
}
if(document.forms.contactform.email.value == "")
{
alert("Please provide an Email address.");
document.forms.contactform.email.focus();
return false;
}else{
var validformat=validateemail();
if(validformat==false)
{
return false;
}}
if(document.forms.contactform.phone.value=="")
{
alert("Please provide a phone number in the format 999-999-9999.");
document.forms.contactform.phone.focus();
return false;
}
else if(document.forms.contactform.phone.value.length < 12)
{
alert("Please provide the phone number in the format of 999-999-9999.");
document.forms.contactform.phone.focus();
return false;
}
else
{
var validnumber=validatephonenumber();
if(validnumber==false)
{
return false;
}}
if(document.forms.contactform.msg.value=="")
{
alert("Please provide a message.");
document.forms.contactform.msg.focus();
return false;
}
return(true);
}

It's unclear without more code but based on your comment I am going to guess that you have incorrectly written your php and it's breaking your javascript/html code. Perhaps one of your quotes? Look at the source code of the page and run it through one of the online validation services such as http://validator.w3.org and http://www.jslint.com

Try this:
PHP HTML:
<?php
echo "<form name='contactform' id='contactform' method='post'
action='' onsubmit='return validateentry(this);'>"
...
Validation JavaScript:
function validateemail(e)
{
var emailentry = e.value
, at = emailentry.indexOf("#")
, period = emailentry.lastIndexOf(".");
if(at < 1 || ( period - at < 2 ))
{
alert("Please enter correct email in the format of 'yourmail#yourwebsite.com'")
e.focus();
return false;
}
return true;
}
function validatephonenumber(e)
{
var re = /(?:\d{3}|\(\d{3}\))([-\/\.])\d{3}\1\d{4}/
, numbers = e.value;
if (!re.exec(numbers))
{
alert("Please enter a phone number in the format of 999-999-9999");
e.focus();
return false;
}
return true;
}
function validateentry(f)
{
if(f.name.value == "")
{
alert("Please provide your name.");
f.name.focus();
return false;
}
if(f.company.value == "")
{
alert("Please provide your company name. If you don't have one, simply state
that you don't.");
f.company.focus();
return false;
}
if(f.email.value == "")
{
alert("Please provide an Email address.");
f.email.focus();
return false;
}
else
{
var validformat = validateemail(f.email);
if(validformat == false)
{
return false;
}
}
if(f.phone.value == "" || f.phone.value.length < 12 || (validnumber = validatephonenumber(f.phone)) == false)
{
alert("Please provide the phone number in the format of 999-999-9999.");
f.phone.focus();
return false;
}
if(f.msg.value == "")
{
alert("Please provide a message.");
f.msg.focus();
return false;
}
return true;
}

Related

I am trying to use use this validation in my html tag by using onsubmit=return validateForm()

//this is the javascript program for validation
function validateForm()
{
var name=document.myform.uname.value;
var password=document.myform.password.value;
var conpass = document.myform.repassword.value;
boolean valid = true;
if(password != conpass)
{
alert("password is not same");
valid=false;
}
else if(name==null || name=="")
{
alert("User Name should not be blank..");
valid=false;
}
else if(password==""|| password==null)
{
alert("Password should not be blank");
valid=false;
}
else if(!this.form.checkbox.checked)
{
alert('You must agree to the terms first.');
return false;
}
else{
return valid;
}
};
//and this is the html in which I am using this but it is not working properly,it is not taking the js validation and directly forwarding me to the reg.jsp page.
<form action="reg.jsp" name="myform" method="post" onsubmit="return validateForm()" >
In order to prevent submit via javascript, you have to return false in your onsubmit handler.
So the in the following line the validateForm() must return false:
<form action="reg.jsp" name="myform" method="post" onsubmit="return validateForm()" >
You have many if-else blocks that set the var valid = false and this is ok.
But this valid variable should be returned. You do this only in the last else blocks.
else if(!this.form.checkbox.checked)
{
alert('You must agree to the terms first.');
return false;
}
else{
return valid;
}
The previous checks are just preparing the variable, but don't return it.
And this is what you need to do.
Here is an example how it can be done:
function validateForm() {
var name=document.myform.uname.value;
var password=document.myform.password.value;
var conpass = document.myform.repassword.value;
var valid = true;
var message = "everything is valid";
if(password != conpass)
{
message = "password is not same";
valid = false;
}
else if(name==null || name=="")
{
message = "User Name should not be blank..";
valid = false;
}
else if(password==""|| password==null)
{
message = "Password should not be blank";
valid = false;
}
else if(!this.form.checkbox.checked)
{
message = "You must agree to the terms first.";
valid = false;
}
alert(message);
return valid;
};
Other improvement could be:
Reordering the conditions by descending importance.
For example: if the Term are not accepted, is not important, if the password is empty.
If password is empty, it is not important, if the conpass is the same.
Using html5, which hast more input types and adjustable build-in validation for common cases. See more here: http://html5doctor.com/html5-forms-input-types/

ELSE IF Statement not validating information

Validate form has been working fine but I have now tried adding email validation to the code and now nothing will validate, form submits without any popup error boxes.
Here's The Current Code:
<script type="text/javascript">
function validateForm(){
var a=document.forms["order_form"]["fname"].value;
var b=document.forms["order_form"]["address"].value;
var c=document.forms["order_form"]["city"].value;
var d=document.forms["order_form"]["pcode"].value;
var e=document.forms["order_form"]["email"].value;
var atpos=email.indexOf("#").value;
var dotpos=email.lastIndexOf(".").value;
if (a==null || a=="")
{
alert("Full name must be filled out");
return false;
}
else if (b==null || b=="")
{
alert("Address must be filled out");
return false;
}
else if (c==null || c=="")
{
alert("City must be filled out");
return false;
}
else if (d==null || d=="")
{
alert("Post-Code must be filled out");
return false;
}
else if (e==null || e=="")
{
alert("Email Address must be filled out");
return false;
}
else if (atpos<1||dotpos<atpos+2||dotpos+2>=email.length)
{
alert("Not a valid e-mail address");
return false;
}
}
</script>
Form is likely submitting due to the following errors
Change:
var atpos=email.indexOf("#").value;
var dotpos=email.lastIndexOf(".").value;
To
var atpos=e.indexOf("#");
var dotpos=e.lastIndexOf(".");
indexOf() returns a number not an object so there is no value property.
Also as noticed by #fpierrat email should be e
I don't see any declaration for email before following:
var atpos=email.indexOf("#").value;
var dotpos=email.lastIndexOf(".").value;
Maybe you meant e, not email?
Also delete the .value after indexof() calls, see #charlieftl's answer, we were quite complementary on this ;-)

javascript confirm cancel still submits form

I have the following sequence on a form page, first it runs through the captcha then it validates the email address and then asks if you are sure you want to unsubscribe.
Everything works perfectly except that clicking "Cancel" still submits the form. I can't use "onclick" in the submit button because it will bypass the captcha code. In my "if the email is true 'else'" statement I've tried both "return" and "return:false" but neither of them stop the form submission.
Thanks for your help.
<form action='<?php echo $_SERVER['PHP_SELF']; ?>' name="unsubscribe" method='post' onsubmit="return checkForm(this);"">
function checkForm(form) {
var frm = document.unsubscribe;
if(!form.captcha.value.match(/^\d{5}$/)) {
alert('Please enter the CAPTCHA digits in the box provided');
form.captcha.focus();
return false;
}
if (validEmail(frm.Email.value) != true) {
alert("Please enter a valid email address");
frm.Email.focus();
return false;
}
if (validEmail(frm.Email.value) == true) {
confirm('Are you sure you want to unsubscribe?');
return true;
}
else {
return false;
}
}
function validEmail(email){
var status = false;
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (email.search(emailRegEx) == -1) {
status = false;
}
else {
status = true;
}
return status;
}
confirm returns a boolean - true if the user clicked "Ok", false if they clicked "Cancel", so simply return the result of the confirm call:
if (validEmail(frm.Email.value) == true) {
return confirm('Are you sure you want to unsubscribe?');
}

Input validation with regex

I am trying to validate the PHP page input with regular expression but I am totally new here and need some assistance
<script>
function addplaces()
{
valid=true;
placename=document.getElementById("placename").value;
city=document.getElementById("city").value;
province=document.getElementById("province").value;
country=document.getElementById("country").value;
category=document.getElementById("category").value;
placepicture=document.getElementById("placepicture").value;
descp=document.getElementById("descp").value;
if(placename=="" || preg_match("^[A-Z]'?[- a-zA-Z]( [a-zA-Z])*$", placename))
{
alert("Please Enter Place Name");
document.getElementById("placename").focus();
valid=false;
}
else if(city=="")
{
alert("Please Enter City Name");
document.getElementById("city").focus();
valid=false;
}
else if(province=="")
{
alert("Please Enter province Name");
document.getElementById("province").focus();
valid=false;
}
else if(country=="")
{
alert("Please Enter country Name");
document.getElementById("country").focus();
valid=false;
}
else if(category=="")
{
alert("Please Enter category Name");
document.getElementById("category").focus();
valid=false;
}
else if(placepicture=="")
{
alert("Please Enter place picture");
document.getElementById("placepicture").focus();
valid=false;
}
else if(descp=="")
{
alert("Please Enter Description");
document.getElementById("descp").focus();
valid=false;
}
return valid;
}
</script>
I try to use preg_match(); but it does not work, please let me know where I am making a mistake.
preg_match is for PHP, that's why it doesn't work in your javascript code.
instead of preg_match("^[A-Z]'?[- a-zA-Z]( [a-zA-Z])*$" (you missed a ) here if you would programming in PHP)
use
var regex = new Regex( /^[A-Z]'?[- a-zA-Z]( [a-zA-Z])*$ );
if(regex.test(placename)) { ... }

Validating form using jQuery.click does not work

Here is my code:
$('input#price_match_submit').click(function(event) {
if ($.trim($('input#price_match_competitor_price').val()) == '') {
alert("Please enter competitor's price.");
return false;
}
if ($.trim($('input#price_match_name').val()) == '') {
alert("Please enter your name.");
return false;
}
if ($.trim($('input#price_match_quantity').val()) == '') {
alert("Please enter the quantity.");
return false;
}
if ($.trim($('input#price_match_email').val()) == '') {
alert("Please enter your email address.");
return false;
}
if ($.trim($('input#price_match_competitor_website').val()) == '') {
alert("Please enter competitor's website.");
return false;
}
if ($.trim($('input#price_match_phone_number').val()) == '') {
alert("Please enter your phone number.");
return false;
}
});
Here #price_match_submit is a submit button. When I click on the button, this function should execute and validate the form. But it's not working as I am expecting. The form is being submitted without any validation. Where I am doing wrong?
You might instead want to hook into the submit event of the parent form and need to prevent the default behaviour:
$('#form').on('submit', function (e) {
if (everything_failed) {
e.preventDefault();
return false;
}
});
return false; only stops event bubbling I think.
You can validate like this
$('form').on('submit', function() {
// do validation here
if ($.trim($('input#price_match_competitor_price').val()) == '') {
alert("Please enter competitor's price.");
return false;
}
if ($.trim($('input#price_match_name').val()) == '') {
alert("Please enter your name.");
return false;
}
if ($.trim($('input#price_match_quantity').val()) == '') {
alert("Please enter the quantity.");
return false;
}
if ($.trim($('input#price_match_email').val()) == '') {
alert("Please enter your email address.");
return false;
}
if ($.trim($('input#price_match_competitor_website').val()) == '') {
alert("Please enter competitor's website.");
return false;
}
if ($.trim($('input#price_match_phone_number').val()) == '') {
alert("Please enter your phone number.");
return false;
}
});
return false if not validated.
$(#price_match_submit').click(function(event) {
if ($.trim($('input#price_match_competitor_price').val()) == '') {
alert("Please enter competitor's price.");
event.preventDefault();
}
else if ($.trim($('input#price_match_name').val()) == '') {
alert("Please enter your name.");
event.preventDefault();
}
else if ($.trim($('input#price_match_quantity').val()) == '') {
alert("Please enter the quantity.");
event.preventDefault();
}
else if ($.trim($('input#price_match_email').val()) == '') {
alert("Please enter your email address.");
event.preventDefault();
}
else if ($.trim($('input#price_match_competitor_website').val()) == '') {
alert("Please enter competitor's website.");
event.preventDefault();
}
else if ($.trim($('input#price_match_phone_number').val()) == '') {
alert("Please enter your phone number.");
event.preventDefault();
}
// if nothing happened until now, the form will be submited
});
Thank you for all your answer and comment.
This code works fine. There was some issue with other parts of code.
When we assign a function to an element, the function is assigned to that physical element only. But when we do some physical modification to the elements, all its previous properties get lost. In my code, I was displaying this html in a modal popup. Which was copying the html instead of using the same elements. So, it lost this binding with the function. And this is the reason this code was not working.

Categories