It's pretty much as the question suggests, I have a HTML form with JS validation. Now, I'm still debugging fine details with the validation, but the problem is that the onSubmit function fires the errors when they should be, but the form continues to submit - I have no idea why. I've check the million and one similar problems on StackOverflow, but none seem to have the same cause as mine - I've checked and check and checked. If anyone could help, I'd greatly appreciate it.
Also, I know my code can be shortened, but I'll do that when I figure this problem out.
Form:
<form name="registerForm" method="post" action="index.php" onSubmit="return validateForm()">
<table class="formTable" >
<tr>
<td><i class="smallprint">* denotes a required field.</i></td>
</tr>
<tr>
<td>
<input type="text" maxlength="32" width="32" name="regTxtUsrName">
</td>
<td>
User Name* <i class="smallprint"> between 6 and 32 characters (letters, numbers and underscores only)</i><br />
<b class="error" id="userNameError">Error: Please enter a user name between 6 and 32 characters, using letters, numbers and underscores</b>
</td>
</tr>
<tr>
<td>
<input type="text" maxlength="32" width="32" name="regTxtFName">
</td>
<td>
First Name*<br />
<b class="error" id="fNameError">Error: Please enter your first name</b>
</td>
</tr>
<tr>
<td>
<input type="text" maxlength="32" width="32" name="regTxtSName">
</td>
<td>
Surname*<br />
<b class="error" id="sNameError">Error: Please enter your surname</b>
</td>
</tr>
<tr>
<td>
<input type="text" maxlength="32" width="32" name="regTxtEmail">
</td>
<td>
Email* <i class="smallprint">Please use a valid email address, it will be used to validate your account</i><br />
<b class="error" id="emailError1">Error: Please enter an email address<br /></b>
<b class="error" id="emailError2">Error: This is not a valid email address</b>
</td>
</tr>
<tr>
<td>
<input type="text" maxlength="32" width="32" name="regTxtEmailConf">
</td>
<td>
Confirm Email*<br />
<b class="error" id="emailConfError">Error: Both email addresses must match</b>
</td>
</tr>
<tr>
<td>
<input type="password" maxlength="32" width="32" name="regTxtPassword">
</td>
<td>
Password* <i class="smallprint">Between 6 and 32 characters, using at least one letter and one number</i><br />
<b class="error" id="passwordError">Error: Please enter a valid password</b>
</td>
</tr>
<tr>
<td>
<input type="password" maxlength="32" width="32" name="regTxtPasswordConf">
</td>
<td>
Confirm Password*<br />
<b class="error" id="passwordConfError">Error: Both email passwords must match</b>
</td>
</tr>
</table>
<br />
<div class="textCenter">
<input type="checkbox" class="center" name="regChkTos"> - Check this box if you agree to the Terms of Service. You must agree in order to regster.
<br />
<br />
<input type="submit" name="regSubmit" value="Register">
</div>
</form>
JS:
<script type="text/javascript">
function validateForm()
{
var noError = true;
if (!validateUserName())
{
noError = false;
}
if (!validateFName())
{
noError = false;
}
if (!validateSName())
{
noError = false;
}
if (!validateEmail())
{
noError = false;
}
if (!validateConfirmEmail())
{
noError = false;
}
if (!validatePassword())
{
noError = false;
}
if (!validateConfirmPassword())
{
noError = false;
}
return noError;
}
function validateUserName()
{
var userName = document.forms["registerForm"]["regTxtUsrName"];
var regex = /^\w+$/;
if (userName.value==null || userName.value=="" || userName.value.length < 6 || !regex.test(userName.value))
{
userName.style.border = "2px solid red";
document.getElementById('userNameError').style.display="inline";
return false;
}
else
{
userName.style.border = "2px solid #0f0";
document.getElementById('userNameError').style.display="none";
return true;
}
}
function validateFName()
{
var name = document.forms['registerForm']['regTxtFName'];
if (name.value == null || name.value == '')
{
name.style.border = "2px solid red";
document.getElementById('fNameError').style.display="inline";
return false;
}
else
{
name.style.border = "2px solid #0f0";
document.getElementById('fNameError').style.display="none";
return true;
}
}
function validateSName()
{
var name = document.forms['registerForm']['regTxtSName'];
if (name.value == null || name.value == '')
{
name.style.border = "2px solid red";
document.getElementById('sNameError').style.display="inline";
return false;
}
else
{
name.style.border = "2px solid #0f0";
document.getElementById('sNameError').style.display="none";
return true;
}
}
function validateEmail()
{
noError = true;
var email = document.forms['registerForm']['regTxtEmail'];
var atpos=email.value.indexOf("#");
var dotpos=email.value.lastIndexOf(".");
if (email.value == null || email.value == '')
{
email.style.border = '2px solid red';
document.getElementById('emailError1').style.display='inline';
noError = false;
}
else
{
document.getElementById('emailError1').style.display='none';
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.value.length)
{
email.style.border = '2px solid red';
document.getElementById('emailError2').style.display='inline';
noError = false;
}
else
{
email.style.border = '2px solid #0f0';
document.getElementById('emailError2').style.display='none';
}
}
return noError
}
function validateConfirmEmail()
{
var email = document.forms['registerForm']['regTxtEmail'];
var emailConf = document.forms['registerForm']['regTxtEmailConf'];
if (email.value != emailConf.value)
{
emailConf.style.border = '2px solid red';
document.getElementById('emailConfError').style.display = 'inline';
return false
}
else
{
emailConf.style.border = '2px solid 0f0';
document.getElementById('emailConfError').style.display = 'none';
return true
}
}
function validatePassword()
{
var password = document.forms['registerForm']['regTxtPassword'];
if (password.value == null || password.value == '' || password.value.length < 6 || password.value.search(/\d/) == -1 || password.value.search(/[A-z]/) == -1)
{
password.style.border = '2px solid red';
document.getElementById('passwordError').style.display = 'inline';
return false;
}
else
{
password.style.border = '2px solid 0f0';
document.getElementById('passwordError').style.display = 'none';
return true;
}
}
function validatePasswordConf()
{
var password = document.forms['registerForm']['regTxtPassword'];
var passwordConf = document.forms['registerForm']['regTxtPasswordConf'];
if (password.value != passwordConf.value)
{
passwordConf.style.border = '2px solid red';
document.getElementById('passwordConfError').style.display = 'inline';
return false;
}
else
{
passwordConf.style.border = '2px solid 0f0';
document.getElementById('passwordConfError').style.display = 'none';
return true;
}
}
</script>
Yes, this script is on the HTML page where the form is located. I've left every field blank, clicked submit, the errors pop up temporarily, then action="index.php" is invoked anyway.
Thanks for any help at all.
first you need to know where the bug is.
For that, use console.log on each function.
After, your code can be optimized with a better algorithm and regex.
To know where the problem is check each return of each function.
For the main function I will do somthing like that :
function validateForm(){
if (validateUserName() && validateFName() && validateSName() && validateEmail() && validateConfirmEmail() && validatePassword() && validateConfirmPassword()){
return true;
}
return false;
}
edit : check the value of your main function too.
do you have a link for this page directly ?
Related
I have a contact us form with captcha .I submit button click I need to perform a serverside captcha validation using a first AJAX request if success then I call the second AJAX/Jquery/php to send contact us mail .
but the first AJAX call is success ,but second one is not calling .. kindly help me on this ..
<form
id="RegisterUserForm"
name="RegisterUserForm"
action=""
onsubmit="return submitform();"
method="post">
<fieldset
style="border: 0;">
<table
width="100%">
<tr>
<td
width="150">
<div
class="celebrationContent">
Name:</div>
</td>
<td
class="style1">
<input
id="Name"
type="text"
name="Name"
style="border-style: none; background-color: #fffcc4;
width: 275px;"
/>
</td>
</tr>
<tr>
<td>
<div
class="celebrationContent">
E-mail
id:</div>
</td>
<td
class="style1">
<input
id="email"
type="text"
name="email"
style="border-style: none; background-color: #fffcc4;
width: 274px;"
/>
</td>
</tr>
<tr>
<td
class="celebrationContent">
Phone
Number:
</td>
<td
class="style1">
<input
id="phonenumber"
type="text"
name="phonenumber"
style="border-style: none;
background-color: #fffcc4; width: 274px;"
/>
</td>
</tr>
<tr>
<td
class="celebrationContent">
Your
Celebration:
</td>
<td
class="style1">
<input
id="yourCelebration"
type="text"
name="yourCelebration"
style="border-style: none;
background-color: #fffcc4; width: 274px; height: auto;"
/>
</td>
</tr>
<tr>
<td
class="celebrationContent">
When
is
it:
</td>
<td
class="style1">
<input
type="text"
name="datepicker"
id="datepicker"
style="border-style: none; background-color: #fffcc4;
width: 272px;"
/>
</td>
</tr>
<tr>
<td
class="celebrationContent">
Enquiry:
</td>
<td
class="style1">
<input
type="text"
id="Enquiry"
name="Enquiry"
style="border-style: none; background-color: #fffcc4;
width: 272px; height: 70px;"
/>
</td>
</tr>
<tr>
<td
colspan="2"
align="left"
class="celebrationContent">
Verification
Code
</td>
</tr>
<tr>
<td
align="left"
colspan="2">
<table
width="100%">
<tr>
<td
width="32%">
<img
src="captcha.php"
alt="celebration captcha"
/>
</td>
<td>
<input
type="text"
id="verificationcode"
name="verificationcode"
style="border-style: none;
background-color: #fffcc4"
/>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td
colspan="2"
align="center">
<input
type="submit"
id="form_submit"
/>
</td>
</tr>
</table>
</fieldset>
</form>
jquery code is
<script type="text/javascript">
$(function () {
$('#datepicker').datepicker('option', 'dateFormat', 'dd-mm-yy');
});
$("#datepicker").datepicker({
minDate: 0
});
function submitform() {
if (validateCaptach()) {
var sData = $("#RegisterUserForm").serialize();
alert('i am here to process..');
$.ajax({
type: "POST",
url: "thankyou.php",
data: sData,
//async: false,
success: function (data) {
if (data == "YESSUCCESS") {
alert("Your Query has been sent..");
return true;
} else {
alert("some error please type again...");
return false;
}
}
});
}
return false;
}
function validateCaptach() {
if (validateForm()) {
var captchaval = $("#verificationcode").val();
$.ajax({
type: "POST",
url: "captchacheck.php",
async: false,
data: {
verificationcode: captchaval
},
success: function (data) {
if (data == "SUCCESS") {
alert("captchacheck success..");
return true;
} else {
alert("The security code you typed was wrong. Please try again.");
return false;
}
}
});
}
}
function validateForm() {
if (document.RegisterUserForm.Name.value == "") {
alert("Please provide your name!");
document.RegisterUserForm.Name.focus();
return false;
}
if (document.RegisterUserForm.email.value == "") {
var emailID = document.RegisterUserForm.email.value;
atpos = emailID.indexOf("#");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || (dotpos - atpos < 2)) {
alert("Please enter correct email ID")
document.RegisterUserForm.email.focus();
return false;
}
}
if ((document.RegisterUserForm.phonenumber.value == "") || isNaN(document.RegisterUserForm.phonenumber.value)) {
alert("Please enter your phone Number");
document.RegisterUserForm.phonenumber.focus();
return false;
}
if (document.RegisterUserForm.yourCelebration.value == "") {
alert("Please enter your Celebration!");
document.RegisterUserForm.yourCelebration.focus();
return false;
}
if (document.RegisterUserForm.datepicker.value == "") {
alert("Please select date !");
document.RegisterUserForm.datepicker.focus();
return false;
}
if (document.RegisterUserForm.Enquiry.value == "") {
alert("Please Enter your enquiry!");
document.RegisterUserForm.Enquiry.focus();
return false;
}
if (document.RegisterUserForm.verificationcode.value == "") {
alert("Please enter the Verificationcode!");
document.RegisterUserForm.verificationcode.focus();
return false;
}
return (true);
}
</script>
You're not returning anything from validateCaptach(). You return true or false from the AJAX callback function, but those values don't go anywhere.
function validateCaptach() {
if (validateForm()) {
var captchaval = $("#verificationcode").val();
var success;
$.ajax({
type: "POST",
url: "captchacheck.php",
async: false,
data: {
verificationcode: captchaval
},
success: function (data) {
if (data == "SUCCESS") {
alert("captchacheck success..");
success = true;
} else {
alert("The security code you typed was wrong. Please try again.");
success = false;
}
}
});
return success;
}
}
You are not returning a value from your validateCaptach. The return values from success event will not be returned to the calling function the way you have handled the code. So in order for you to get the desired output. You have to make the second call from with in the success event of your ajax call.
for example
.....
success: function(e) {
callSecondFunction();
}
This would be the best approach.
I can't understand why you are using two AJAX requests for this. This doesn't make sence.
You can verify everything in a single AJAX call. Please do captcha check and form submit in
captchacheck.php
As you are working with asynchronous calls, the function validateCaptcha finishes before the ajax call is done. You need to send the second ajax call after the first ajax call has returned sucessfully.
<script type="text/javascript">
$(function(){
$('#datepicker').datepicker('option', 'dateFormat', 'dd-mm-yy');
});
$("#datepicker").datepicker({
minDate: 0
});
function submitform () {
/**
* Pass the second ajax call as a function
*/
validateCaptcha(function(){
var sData = $("#RegisterUserForm").serialize();
alert('i am here to process..');
$.ajax({
type: "POST",
url: "thankyou.php",
data: sData,
//async: false,
success: function (data) {
if (data == "YESSUCCESS") {
alert("Your Query has been sent..");
return true;
}
else {
alert("some error please type again...");
return false;
}
}
});
});
return false;
}
function validateCaptcha (action) {
if (validateForm()) {
var captchaval = $("#verificationcode").val();
$.ajax({
type: "POST",
url: "captchacheck.php",
async: false,
data: {
verificationcode: captchaval
},
success: function (data) {
if (data == "SUCCESS") {
alert("captchacheck success..");
if (typeof action == "function") {
action();
}
return true;
}
else {
alert("The security code you typed was wrong. Please try again.");
return false;
}
}
});
}
}
function validateForm () {
if ($("#RegisterUserForm [name=Name]").val() == "") {
alert("Please provide your name!");
$("#RegisterUserForm [name=Name]").focus();
return false;
}
if ($("#RegisterUserForm [name=email]").val() == "") {
var emailID = $("#RegisterUserForm [name=email]").val();
atpos = emailID.indexOf("#");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || (dotpos - atpos < 2)) {
alert("Please enter correct email ID")
$("#RegisterUserForm [name=email]").focus();
return false;
}
}
if (($("#RegisterUserForm [name=phonenumber]").val() == "") || isNaN($("#RegisterUserForm [name=phonenumber]").val())) {
alert("Please enter your phone Number");
$("#RegisterUserForm [name=phonenumber]").focus();
return false;
}
if ($("#RegisterUserForm [name=yourCelebration]").val() == "") {
alert("Please enter your Celebration!");
$("#RegisterUserForm [name=yourCelebration]").focus();
return false;
}
if ($("#RegisterUserForm [name=datepicker]").val() == "") {
alert("Please select date !");
$("#RegisterUserForm [name=datepicker]").focus();
return false;
}
if ($("#RegisterUserForm [name=Enquiry]").val() == "") {
alert("Please Enter your enquiry!");
$("#RegisterUserForm [name=Enquiry]").focus();
return false;
}
if ($("#RegisterUserForm [name=verificationcode]").val() == "") {
alert("Please enter the Verificationcode!");
$("#RegisterUserForm [name=verificationcode]").focus();
return false;
}
return true;
}
</script>
i have inserted the information in my database and also i have validate it. but if i click to insert it is redirecting to another page. i want to done this operation in AJAX concepts please help me. Thanks in Advance
HTML coding
<form id="myform" action="bl/checkout_report.php?action=check_out" method="post" name="myform">
<table width="200" border="0">
<h3><u><b>Shipping Details</b></u></h3>
<tr>
<th scope="row"><label>Name*</label></th>
<td><input id="fname" name="fname" type="text" class="shipping-required"></td>
</tr>
<tr>
<th scope="row"><label>Shipping Address*</label>;</th>
<td><textarea name="address" id="address" class="shipping-required"></textarea></td>
</tr>
<tr>
<th scope="row"><label>Nearest Landmark*</label></th>
<td><textarea name="land" id="land" class="shipping-required"></textarea></td>
</tr>
<tr>
<th scope="row"><label>City*</label></th>
<td><input id="city" name="city" type="text" class="shipping-required"></td>
</tr>
<tr>
<th scope="row"><label>State*</label></th>
<td><select id="state" name="state"> <option selected="" value="Default" class="shipping- required">(Please select a state)</option>
<option>Andhara Pradesh</option>
<option>Assam</option>
<option>Bihar</option>
<option>Delhi</option>
<option>Gujarat</option>
<option>Tamil Nadu</option>
</select></td>
</tr>
<tr>
<th scope="row"><label>Pin Code*</label></th>
<td><input id="code" name="code" type="text" class="shipping-required"></td>
</tr>
<tr>
<th scope="row"><label>Mobile Number*</label></th>
<td><input id="mobile1" name="mobile1" type="text" class="shipping-required"></td>
</tr>
<tr>
<th scope="row"> <label>Mail id</label></th>
<td><input id="mail1" name="mail1" type="text" class="shipping-required"></td>
</tr>
<td><input type="hidden" id="pwd" name="pwd" value="<?php echo "$password"?>"></td>
<tr>
<td><input id="submit" name="submit" type="submit" value=" Continue" onclick="return formValidate()"></td>
</tr>
</table>
</form>
JAVASCRIPT validate function
function formValidate() {
alert("ok");
var fname = document.myform.fname;
var address = document.myform.address;
var land = document.myform.land;
var city = document.myform.city;
var state = document.myform.state;
var code = document.myform.code;
var mobile1 = document.myform.mobile1;
var mail1 = document.myform.mail1;
if (item1(fname)) {
if (idd(address)) {
if (lad(land)) {
if (place(city)) {
if (native(state)) {
if (pin(code)) {
if (number(mobile1)) {
if (id(mail1)) {
document.myform.submit();
}
}
}
}
}
}
}
}
return false;
}
function item1(fname) {
if (fname.value != "") {
var letters = /^[A-Z a-z]+$/;
if (fname.value.match(letters)) {
return true;
} else {
alert('nbumber');
fname.focus();
return false;
}
} else {
alert(' Name should not empty');
fname.focus();
}
}
function idd(address) {
if (address.value != "") {
var letters = /^[a-zA-Z0-9\s,'-]*$/;
if (address.value.match(letters)) {
return true;
} else {
alert('Enter Valid Address ');
address.focus();
return false;
}
} else {
alert('Address should not empty');
address.focus();
}
}
function lad(land) {
if (land.value != "") {
var letters = /^[a-zA-Z0-9\s,'-]*$/;
if (land.value.match(letters)) {
return true;
} else {
alert('Enter Valid Land Mark ');
land.focus();
return false;
}
} else {
alert('Land Mark should not empty');
land.focus();
}
}
function place(city) {
if (city.value != "") {
var letters = /^[A-Z a-z]+$/;
if (city.value.match(letters)) {
return true;
} else {
alert(" City Must have alphabet Charater Only");
city.focus();
return false;
}
} else {
alert('city should not empty');
}
}
function native(state) {
if (state.value == "Default") {
alert('Select your State from the list');
state.focus();
return false;
} else {
return true;
}
}
function pin(code) {
if (code.value != "") {
var uadd_len = code.value.length;
if (uadd_len == 6) {
return true;
} else {
alert(" Pin Code Must Have six Numbers");
code.focus();
return false;
}
} else {
alert('Pincode should not empty');
}
}
function number(mobile1) {
if (mobile1.value != "") {
var uadd_len = mobile1.value.length;
if (uadd_len == 10) {
return true;
} else {
alert('Enter 10 Digit Mobile Number ');
mobile1.focus();
return false;
}
} else {
alert('Mobile Number should not empty');
mobile1.focus();
}
}
function id(mail1) {
if (mail1.value != "") {
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (mail1.value.match(mailformat)) {
return true;
} else {
alert('Invalid Mail Format ');
mail.focus();
return false;
}
} else {
alert('Mail should not empty');
mail1.focus();
}
}
You can either write your own Ajax script XHR Create object or use existing libraries like jQuery to ease the work for you
http://api.jquery.com/jQuery.post/
$("#foo").submit(function(event){
var request = $.ajax({
url: "/checkout_report.php",
type: "post",
data: serializedData
});
});
Check the existing ex in stackoverflow: jQuery Ajax POST example with PHP
Have you tried jquery submit.
(function($)
{
$('#form').submit(function()
{
//check for validation..
return false;
});
});
If you don't want to use jQuery then you should try http://www.simonerodriguez.com/ajax-form-submit-example/.
You can use jquery form plugin for this.
This plugin can help you to upload files too.
So I think it is best for you
Here is docs for this plugin http://malsup.com/jquery/form/
And examples are here http://malsup.com/jquery/form/#ajaxForm
Your function formValidate is very complex try to write this in simple way for egs:
function formValidate()
{
alert("ok");
var fname = document.myform.fname;
var address = document.myform.address;
var land = document.myform.land;
var city = document.myform.city;
var state = document.myform.state;
var code = document.myform.code;
var mobile1 = document.myform.mobile1;
var mail1 = document.myform.mail1;
var status=true;
if(!item1(fname))
{
status=false;
}
if(!idd(address))
{
status=false;
}
if(!lad(land))
{
status=false;
}
if(!place(city))
{
status=false;
}
if(!native(state))
{
status=false;
}
if(!pin(code))
{
status=false;
}
if(!number(mobile1))
{
status=false;
}
if(!id(mail1))
{
status=false;
}
//thinking all functions return true or false
if(status)
document.myform.submit();
return status;
}
I am trying to add ReCaptcha into a mail form that I created which is intended for sharing content,
but for some reason the captcha is not being validated when I hit "submit", meaning that even if you enter a wrong text in the captcha, the form will still send the email.
I am using joomla 2.5.8, the recaptcha plugin is enabled (although I don't think it is being intialized since I added the recaptchalib.php myself and I am including the ref to the publickey and privatekey inside the mail form code).
Any help would be very much appreciated!
Thank you!!
here is the code:
<?php require_once('recaptchalib.php'); ?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="javascript" type="text/javascript">
function validateEmail($email)
{
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if( !emailReg.test( $email ) )
{
return false;
}
else
{
return true;
}
}
function validateForm()
{
var form = document.mailForm;
if (form.recipient.value == "" || validateEmail(form.recipient.value)==false)
{
alert("bad email");
return false;
}
if (form.subject.value == "")
{
alert("please enter subject");
return false;
}
if (form.content.value == "")
{
alert("please enter massage");
return false;
}
<?php
$privatekey = "privatekey";
$resp = recaptcha_check_answer($privatekey,$_SERVER["REMOTE_ADDR"],$_POST["recaptcha_challenge_field"],$_POST["recaptcha_response_field"]); ?>
if (!$resp->is_valid)
{
alert("try again");
return false;
}
return true;
}
</script>
<?php
if($this->success=='1')
{
echo JText::_('MAIL_SEND_SUCCESSFULLY');
}
elseif($this->success=='0')
{
echo JText::_('MAIL_SEND_FAILED');
}
?>
<div id="SendMail">
<h2>send mail</h2>
<form action="index.php" name="mailForm" method="post" onsubmit="return validateForm()">
<table>
<tr>
<td><label><?php echo JText::_('MAIL_SEND_TO'); ?>:</label></td>
<td><input type="text" name="recipient" size="25" value=""/></td>
</tr>
<tr>
<td><label><?php echo JText::_('MAIL_SUBJECT'); ?>:</label></td>
<td><input type="text" name="subject" size="25" value=""/></td>
</tr>
<tr>
<td><label><?php echo JText::_('MAIL_MESSAGE'); ?>:</label></td>
<td>
<textarea name="content" rows="10" cols="40"></textarea>
<br/><?php echo JText::_('MAIL_DESC'); ?>
</td>
<tr>
<td><?php $publickey = "public key"; ?></td>
<td><?php echo recaptcha_get_html($publickey);?></td>
</tr>
</table>
<p>
<input type="hidden" name="controller" value="mail" />
<input type="hidden" name="task" value="sendMail" />
<div class="button-mail">
<input style="width: 50px;height: 25px;" type="submit" name="submit" value="<?php echo JText::_('SEND'); ?>"/>
<a href="javascript: void window.close()" title="Close Window"><span style="color: #444;
border: #D5D5D5 1px solid; padding: 4px; width: 50px;height: 25px;"><?php echo JText::_('CLOSE'); ?></span></a>
</div>
</p>
</form>
</div>
You have error in the code. Please look this lne
if (!$resp->is_valid)
{
alert("try again");
return false;
}
Where $resp->is_valid is the PHP but executed as JS.
Correct code would be
if (!<php (int)$resp->is_valid;?>)
{
alert("try again");
return false;
}
But it will not work anyway because of 2.
You cannot check recaptcha code in Javascript validation. It should be checked server side. Or if you want to check with javascript it should be checked with AJAX request to server. That is because you code
<?php
$privatekey = "privatekey";
$resp = recaptcha_check_answer($privatekey,$_SERVER["REMOTE_ADDR"],$_POST["recaptcha_challenge_field"],$_POST["recaptcha_response_field"]); ?>
is executed on form load before even user eneter captcha.
I am creating a page in which I am fetching data from table and showing data in textbox to allow user to update record. I also validate the user input to textbox. But the problem is when the user does not change any field and click on submit, it validates username field i.e. it always wants to change (or edit textbox) the value of textboxes.
Here is my code:
<?php
include("conn.php");
$id=$_GET['id'];
$sql="SELECT * FROM test WHERE id='$id'";
$res=mysql_query($sql);
$row=mysql_fetch_array($res);
?>
<script type='text/javascript'>
function formValidator()
{
// Make quick references to our fields
alert("hiiiiiii");
var name = document.getElementById('name').value;
var email = document.getElementById('emailid').value;
var ph = document.getElementById('ph').value;
if( name=="" || name==null)
{
alert("Please Enter user name");
return false;
}
var alphaExp = /^[a-zA-Z]+$/;
if(!name.match(alphaExp))
{
alert("please Enter only Alphabates for Name");
return false;
}
if(email=="" || email=="null")
{
alert("Please Enter Email Address");
return false;
}
var emailExp = /^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
if(!email.match(emailExp))
{
alert("please Enter valide email address");
return false;
}
if(ph=="" || ph=="null")
{
alert("Please Enter Phone Number");
return false;
}
var numericExpression = /^[0-9]+$/;
if(!ph.match(numericExpression))
{
alert("Enter only Digit for Phone Number");
return false;
}
}
</script>
<form name="updateform" method="POST" action="update_ind_new.php" onsubmit='return formValidator()'>
<table width="200" border="0">
<tr>
<td>User Name</td>
<td>E-Mail</td>
<td>phno</td>
</tr>
<tr>
<td><label>
<input name="name" type="text" id="name" value=" <?php echo $row['name']; ?>" >
</label></td>
<td><label>
<input name="email" type="text" id="emailid" value=" <?php echo $row['emailid']; ?>" >
</label></td>
<td><label>
<input name="ph" type="text" id="ph" value=" <?php echo $row['phno']; ?>" >
</label></td>
</tr>
<tr>
<td> <input name="id" type="hidden" id="id" value=" <?php echo $row['id']; ?>"></td>
<td><label>
<input type="submit" name="Submit" value="Submit">
</label></td>
<td> </td>
</tr>
</table>
</form>
write return true; at the end of this line
if(!ph.match(numericExpression))
{
alert("Enter only Digit for Phone Number");
return false;
}
return true;
Put return true; at the end of all the conditions in the validation function
or put a validations in "if else if else" conditions
I have created a "signup" page on my site, but the javascript validation function does not seem to call when the "onsubmit" event is fired. I have already read the posts on this site regarding a similar issue, but their problem seems to be that they forgot to return a boolean value indicating to go ahead and perform the action. Note that this page is "included" in another page with the php function "include".
<script type="text/javascript">
function validateForm() {
//alert();
var display = document.getElementById('error');
var usernameValue = document.getElementById('username').value;
var passwordValue = document.getElementById('password').value;
var rptPasswordValue = document.getElementById('rptPassword').value;
var emailValue = document.getElementById('email').value;
var aliasValue = document.getElementById('alias').value;
if (usernameValue != '' && passwordValue != '' && rptPasswordValue != '' && emailValue != '' && aliasValue != '') {
if (passwordValue == rptPasswordValue) {
if (usernameValue.length > 32 || aliasValue.length > 32) {
displayError("Username or password is too long (Both fields must contain 32 characters or less)");
} else {
if (passwordValue.length > 32 || passwordValue.length < 4) {
displayError("Password must be between 4 and 32 characters in length.");
} else {
if (emailValue.indexOf('#') == -1 || emailValue.length > 64 || emailValue.length < 6) {
displayError("Please make sure you have entered a valid email. (Emails must be between 6 and 64 characters in length)");
} else {
if (aliasValue < 3 || aliasValue > 32) {
displayError("Your alias must be between 3 and 32 characters in length.");
} else {
return true;
}
}
}
}
} else {
displayError("Please make sure both passwords match.");
}
} else {
displayError("Please make sure each field contains a value.");
}
return false;
}
function displayError(var msg) {
document.getElementById('error').innerHTML = msg;
}
</script>
<h1>Sign Up</h1>
<p>All fields must be filled out in order for an account to be created.</p>
<form onsubmit="return validateForm();" action="register.php" method="post">
<table>
<tr>
<td>
<p class="txtLabel">Username:</p>
</td>
<td>
<input type="text" class="defaultTxt" tabindex="0" id="username" name='username'>
</td>
<td>
<p class="txtLabel">Email Address:</p>
</td>
<td>
<input type="text" class="defaultTxt" tabindex="1" id="email" name='email'>
</td>
</tr>
<tr>
<td>
<p class="txtLabel">Password:</p>
</td>
<td>
<input type="password" class="defaultTxt" tabindex="2" id="password" name='password'>
</td>
</tr>
<tr>
<td>
<p class="txtLabel">Repeat Password:</p>
</td>
<td>
<input type="password" class="defaultTxt" tabindex="2" id="rptPassword" name='rptPassword'>
</td>
</tr>
<tr>
<td>
<p class="txtLabel">Nickname/Alias:</p>
</td>
<td>
<input type="text" class="defaultTxt" tabindex="4" id="alias" name='alias'>
</td>
</tr>
</table>
<p><b id='error' style='color: red'></b></p><br />
<input type="submit" value='' name='submit' class="submitBtn">
</form>
Note that in the validateForm function the alert was used to test if the function was called at all, it isn't.
Any ideas?
function displayError(var msg) {
document.getElementById('error').innerHTML = msg;
}
Replace it with
function displayError(msg) {
document.getElementById('error').innerHTML = msg;
}
In your java-script function you cant write like function displayError(var msg).
Good luck.
Bug in your JavaScript here:
function displayError(var msg) {
^^^
document.getElementById('error').innerHTML = msg;
}
You do not need the var keyword in a methods parameters.