Validate AJAX generated form field - php

I have a form with select Field A. This field can be dynamically populated based on the URL or it can be selected as usual.
Once a value has been selected in Field A either way, select Field B is populated and exposed with JQuery AJAX.
Here is the problem. If Field A is left untouched, and is dynamically populated by the URL, Field B will properly validate. However, if Field A is changed, Field B will no longer attempt to validate.
Field A
<select name="FieldA" id="FieldA">
<option value="">Please Select</option>
<?php
while($FieldA= mysql_fetch_array($result2)) {
?>
<option value="<?php echo $FieldA['FieldAID']; ?>"<?php if ($var == $FieldA['FieldAID']) echo " selected=\"selected\""; ?>><?php echo $FieldA['FieldAName']; ?> </option>
<?php } ?>
</select>
Field B
<select name="FieldB" id="FieldB">
<option value="">Please Select</option>
<?php
while($FieldB = mysql_fetch_array($result)) {
?>
<option value="<?php echo $FieldB['FieldBID']; ?>"><?php echo str_replace('|',' - ',$FieldB['FieldBName']); ?></option>
<?php } ?>
</select>
Validation Criteria
<script language="JavaScript" type="text/javascript">
var frmvalidator = new Validator("FormName");
frmvalidator.addValidation("FieldA","req","Please select FieldA.");
frmvalidator.addValidation("FieldB","req","Please select FieldB.");
</script>
Everything works EXCEPT that the AJAX call breaks the validation for Field B. If Field B is not repopulated, it works fine. Field B is constructed with an include file so it is the same whether populated by the page or the AJAX call.
Thank you!

I suppose you are using this js library:
http://www.javascript-coder.com/html-form/javascript-form-validation.phtml
If it gives you many problems, perhaps it's time to change to a more powerful validation library.
I recommend this:
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
Which appears in jquery webpage, and it is very complete. The syntax is more or less like this:
$("#signupForm").validate({
rules: {
firstname: "required",
lastname: "required",
username: {
required: true,
minlength: 2
},
password: {
required: true,
minlength: 5
},
confirm_password: {
required: true,
minlength: 5,
equalTo: "#password"
},
email: {
required: true,
email: true
},
topic: {
required: "#newsletter:checked",
minlength: 2
},
agree: "required"
},
messages: {
firstname: "Please enter your firstname",
lastname: "Please enter your lastname",
username: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
confirm_password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long",
equalTo: "Please enter the same password as above"
},
email: "Please enter a valid email address",
agree: "Please accept our policy"
}
});

Related

jQuery Validation Plugin add a rule for Google Recaptcha V.2 [duplicate]

This question already has answers here:
how to test Recaptcha with jQuery Validate plugin
(1 answer)
Set reCaptcha field as required
(4 answers)
reCaptcha field as required
(1 answer)
JQuery Validate plugin: how can I make Google reCapture click required?
(2 answers)
Using ReCaptcha with jQuery Validate, giving correct response but gives error
(4 answers)
Closed 2 years ago.
I Have a register page where the Google Recaptcha V.2 is used. I want to add a rule for enter Recaptcha using the jQuery Validation Plugin. In the register page the following code is presented for showing the Google Recaptcha:
<?php if(!$this->K2Params->get('recaptchaV2')): ?>
<label class="formRecaptcha"><?php echo JText::_('K2_ENTER_THE_TWO_WORDS_YOU_SEE_BELOW'); ?></label>
<?php endif; ?>
<div id="recaptcha" name="recaptcha" class="<?php echo $this->recaptchaClass; ?>"></div>
In the rigister.js I added the following code:
jQuery(($)=>{
$().ready(()=>{
// validate signup form on keyup and submit
$("#josForm").validate({
ignore: ".ignore",
rules: {
name: {
required: true,
minlength: 3
},
password: {
required: true,
minlength: 7
},
email: {
required: true,
email: true
},
},
messages: {
name: {
required: "enter your name",
minlength: "no less than 3 symbols"
},
password: {
required: "enter the password",
minlength: "no less than 7 symbols"
},
email: "enter your email",
email: {
required: "enter your email"
},
},
submitHandler: function(form) {
if (recaptcha.getResponse()) {
form.submit();
} else {
alert('Please confirm captcha to proceed')
}
},
});
});
});
But this rule is not worked for Google Recaptcha. Can you help we with this issue?
Ohhh, I add the rule for hiddenRecaptcha and add the hidden input with id and name "hiddenRecaptcha". The correct code is below:
<?php if(!$this->K2Params->get('recaptchaV2')): ?>
<label class="formRecaptcha"><?php echo JText::_('K2_ENTER_THE_TWO_WORDS_YOU_SEE_BELOW'); ?></label>
<?php endif; ?>
<div id="recaptcha" name="recaptcha" class="<?php echo $this->recaptchaClass; ?>"></div>
<input type="hidden" class="hiddenRecaptcha required" name="hiddenRecaptcha" id="hiddenRecaptcha" />
And in register.js:
jQuery(($)=>{
$().ready(()=>{
$("#josForm").validate({
ignore: ".ignore",
rules: {
name: {
required: true,
minlength: 3
},
password: {
required: true,
minlength: 7
},
email: {
required: true,
email: true
},
hiddenRecaptcha: {
required: function() {
if(grecaptcha.getResponse() == '') {
return true;
} else {
return false;
}
}
},
},
messages: {
name: {
required: "enter your name",
minlength: "no less than 3 symbols"
},
password: {
required: "enter the password",
minlength: "no less than 7 symbols"
},
email: "enter your email",
email: {
required: "enter your email"
},
},
});
});
});
Now the rule is worked for Captcha.

Regarding Jquery validation

I put the jquery validation on select filed and i take field name is name="course[]". I take it in array because I want to store multiple selected option in table but when i use this name in validation that time my validation is not working on select field can anyone suggest me any solution.
My jquery code is here:-
<script type="text/javascript">
$("#formValidate").validate({
rules: {
course:{
required: true
},
messages: {
course:{
required: "Enter a username";
},
errorElement : 'div',
errorPlacement: function(error, element) {
var placement = $(element).data('error');
if (placement) {
$(placement).append(error)
} else {
error.insertAfter(element);
}
}
});
</script>
my html field code is here:-
<form class="formValidate" id="formValidate" action="" method="POST">
<select multiple id="course" name="course[]">
<option value="Php">PHP</option>
<option value="ruby">RUBY</option>
<option value="wordpress">WORDPRESS</option>
<option value="java">java</option>
</select>
</form>
The issue is that your field name is course[], not course. Therefore you need to wrap the object key in quotes and include the braces.
Also note that your code has some errors; you've placed a ; within an object which is a syntax error, and you're missing a closing }.
$("#formValidate").validate({
rules: {
'course[]': { // note the quotes and braces here
required: true
},
messages: {
course: {
required: "Enter a username"
},
errorElement: 'div',
errorPlacement: function(error, element) {
var placement = $(element).data('error');
if (placement) {
$(placement).append(error)
} else {
error.insertAfter(element);
}
}
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<form class="formValidate" id="formValidate" action="" method="POST">
<select multiple id="course" name="course[]">
<option value="Php">PHP</option>
<option value="ruby">RUBY</option>
<option value="wordpress">WORDPRESS</option>
<option value="java">java</option>
</select>
<button>Submit</button>
</form>
If you use array add field name with [] along with ' or "
("#formValidate").validate({
rules: {
"course[]":{
required: true
},
messages: {
"course[]":{
required: "Enter a username";
},
errorElement : 'div',
errorPlacement: function(error, element) {
var placement = $(element).data('error');
if (placement) {
$(placement).append(error)
} else {
error.insertAfter(element);
}
}
});
</script>
See my updated code below, it will print validation message 'Enter a username' which not showing on other user's answers as they missed a closing } in rules in their code.
$("#formValidate").validate({
rules: {
'course[]': { required: true }
},
messages: {
'course[]': { required: 'Enter a username' },
errorElement: 'div',
errorPlacement: function(error, element) {
var placement = $(element).data('error');
if (placement) {
$(placement).append(error);
} else {
error.insertAfter(element);
}
}
}
});

jQuery form validation equalTo hidden field

I am working on a form which is validated with jQuery before being submitted. One of the fields is a captcha.
The idea is very simple, the captcha is shown as an image and also stored in a hidden field. When the user enters the captcha in the input field it should be equal to the value of the hidden field. This is the jQuery code I have;
<script>
$(document).ready(function(){
$("#register").validate({
errorElement: 'div', ignore: 'hidden',
rules: {
password: {
required: true
},
password2: {
required: true, equalTo: "#password"
},
agree: {
required: true
},
captcha: {
required: true, equalTo: "#captcha2"
}
},
messages: {
password2: "Please repeat the same password",
captcha: "The captcha you entered is wrong",
agree: "You have to be at least 16 years old and agree to the terms of service"
}
});
});
</script>
The html code for the form is even simpler, but I will show only a part of it.
<p>
<img src='/includes/captcha.php' />
</p>
<p>
<label for="Captcha">Captcha</label>
<em> *</em><input type="text" name="captcha" id="captcha" size="25"
class="require" minlength="5" />
<input type="hidden" name="captcha2" id="captcha2"
value="<?php echo $_SESSION['captcha'];?>" />
This should work. The problem is, however, that I keep getting the error that I set in the jQuery code, "The captcha you entered is wrong".
Can anyone tell me why the code is not working?
BTW, I checked the value of the hidden field and it is the same as the captcha, so that works
UPDATE:
Ok, here is something weird. When I echo the session['captcha'] I get a different value than the value in the hidden field. I get the previous captcha when I echo it. So let's say the captcha value is abc. When I refresh the captcha+hidden field change into def. But when I echo session['captcha'] I still get abc.

Username taken check with jquery validate plugin

I am trying to use the username taken or not using jquery validate plugin. but dosent seems to work. I would like to know where I went wrong, all other validation works fine. except for this.
jquery validate plugin page: http://bassistance.de/jquery-plugins/jquery-plugin-validation/
javascript
<script type="text/javascript">
$(document).ready(function(){
$("#register").validate({
debug: false,
rules: {
username: {
required: true,
minlength: 2,
remote: "users.php"
},
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 5
},
confirm_password: {
required: true,
minlength: 5,
equalTo: "#password"
}
},
messages: {
username: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters",
remote: jQuery.format("{0} is already in use")
},
email: "A valid email will help us get in touch with you.",
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
confirm_password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long",
equalTo: "Please enter the same password as above"
},
submitHandler: function(form) {
// do other stuff for a valid form
$.post('adduser.php', $("#register").serialize(), function(data) {
$("#register").fadeOut('fast', function(){
$('#results').html(data);
});
});
}
});
});
</script>
users.php
<?php
$request = $_REQUEST['username'];
//usleep(150000);
$query = mysql_query("SELECT * FROM users WHERE username ='$username'");
$result = mysql_num_rows($query);
if ($result == 0){
$valid = 'true';}
else{
$valid = 'false';
}
echo $valid;
?>
register.php
<form name="register" id="register" method="post" action="">
<section>
<label for="username">Username:</label>
<div>
<input type="text" tabindex="1" class="input" id="username" name="username" value=""/>
</div>
</section>
<!--#-->
<section>
<label for="email">email</label>
<div>
<input type="text" tabindex="2" class="input" id="email" name="email" value=""/>
</div>
</section>
<!--#-->
<section>
<label for="password">Password</label>
<div>
<input type="password" tabindex="3" class="input" id="password" name="password" value=""/>
</div>
</section>
<!--#-->
<section>
<label for="confirm_password">Confirm Password</label>
<div>
<input type="password" tabindex="4" class="input" id="confirm_password" name="confirm_password" value=""/>
</div>
</section>
<!--#-->
<br/>
<input type="submit" tabindex="5" id="submit" value="REGISTER" />
</form>
<div id="results"> </div>
thanks in advance.
I have the same but I use their validation and this to check if username exists. It works great.
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
//the min chars for username
var min_chars = 3;
//result texts
var characters_error = 'username must have atleast 3 characters';
var checking_html = 'searching...';
//when button is clicked
$('#check_username_availability').click(function(){
//run the character number check
if($('#username').val().length < min_chars){
//if it's bellow the minimum show characters_error text
$('#username_availability_result').html(characters_error);
}else{
//else show the cheking_text and run the function to check
$('#username_availability_result').html(checking_html);
check_availability();
}
});
});
//function to check username availability
function check_availability(){
//get the username
var username = $('#username').val();
//use ajax to run the check
$.post("checkuser.php", { username: username },
function(result){
//if the result is 1
if(result == 1){
//show that the username is available
$('#username_availability_result').html('<span class="is_available"><b>' +username + '</b> is available</span>');
//this is the id of my save button it'll display if available
$('#newacct').css("display", "inline");
}else{
//show that the username is NOT available
$('#username_availability_result').html('<span class="is_not_available"><b>' +username + '</b> is not available</span>');
}
});
}
</script>
First, you have an extra } that is closing your messages option prematurely, leading to the remaining messages being ignored. You should move this } after the confirm_password message block. Second, you should be calling jQuery.validator.format rather than jQuery.format. I believe this is why this particular validation rule doesn't work. Correct these and see if it works for you.
To answer the OP, you might want to use $_GET. Also, mysql_num_rows has been deprecated as of PHP 5.5.0, so you'll probably want to update that. You could just check if the query returns false.
<?php
$request = $_GET['username'];
//usleep(150000);
$query = mysql_query("SELECT * FROM users WHERE username ='$username'");
if ($query == false){
$valid = 'true';} // username available
else{
$valid = 'false'; // username unavailable
}
echo $valid;
?>
Try this......
JS
$("#register").validate({
debug: false,
rules: {
username: {
required: true,
minlength: 6,
remote: {
url: "Your PHP",
type: "post",
data: {
funct: 'user_check',
username: function() {
return $( "#username" ).val();
}
}
}
},
messages: {
username: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters",
remote: jQuery.format("{0} is already in use")
}
});
});
PHP
<?php
function user_check(){
$username = $_POST['username'];
$query = mysql_query("SELECT * FROM users WHERE username ='$username'");
if ($query == false){
$valid = 'true';} // username available
else{
$valid = 'false'; // username unavailable
}
echo $valid;
}
?>
May help..

JQuery Validation is not working

I have one form in which one input type whose value is "First Name". But this can be changed on onfocus function I want validation for this input field if it is blank or "First name"
I have two jQuery files jquery-1.4.2.min.js & jquery.validate.pack.js.
I have another jQuery file for this form:
jQuery(document).ready(function() {
jQuery("#frmRegister").validate({
errorElement:'div',
rules: {
Fname:{
required:true,
minlength: 2,
maxlength:30
}
},
messages: {
Fname:{
required: "Please enter first name",
minlength: "Required minimum 2 characters allowed",
maxlength: "Required maximum 30 characters allowed"
}
});
jQuery("#msg").fadeOut(5000);
});
In this file required:true is working if value is blank but by default value is "First Name" so it does not work I want both if it is blank or it is "First Name".
<form name="frmRegister" id="frmRegister" method="post">
<ul class="reset ovfl-hidden join">
<li class="fall">
<label for="Fname">Full Name:</label>
<div class="fl">
<input type="text" class="form" id="Fname" name="Fname" value="First Name" onfocus="if(this.value=='First Name')this.value='';" onblur="if(this.value=='')this.value='First Name';" />
</div>
</li>
</ul>
</form>
Please reply as early as possible.
Thank you.
You can use required rule with Callback and check for equality with First Name before returning
You should create custom validation rules for such cases as described here: jquery.validation - how to ignore default values when validating mandatory fields
this is my code it's working properly: try this
$().ready(function() {
$("#form2").validate();
// validate signup form on keyup and submit
$("#form1").validate({
rules: {
userid: "required",
username: {
required: true,
minlength: 2
},
password: {
required: true,
minlength: 5
},
authority: {
required: true
},
emailid: {
required: true,
email: true
}
},
messages: {
userid: "Please enter your user Id",
username: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
emailid: "Please enter a valid email address",
authority:"Please select Authority"
},
}
});
Did u try the adding custom validation ]
jQuery.validator.addMethod("workPublicserviceDate",
function(value, element) {
var hint = '<?php echo $dateHint; ?>';
var format = '<?php echo $format; ?>';
var pubService = strToDate($('#txtAPS').val(), format)
var dateAssume = strToDate($('#txtAssumeDate').val(), format);
if (pubService && dateAssume && (pubService > dateAssume)) {
return false;
}
return true;
}, ""
);
Pls note i have added example
$("#frmEmpJobDetails").validate({
rules: {
txtAPS: { workPublicserviceDate: function(){ return ['<?php echo $dateHint; ?>','<?php echo $format; ?>']}, required:true },
}
messages: {
txtAPS : { workPublicserviceDate: '<?php echo __("Invalid date."); ?>',
}

Categories