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);
}
}
}
});
Related
I have seen this example and applied it in my code yet nothing worked, its not working.
Referral ans-1
Referral ans-2
I need to apply jquery validation in ckeditor and I have seen all those past examples even I have mentioned those links above, by doing that step my validation is still not working.
Here is my HTML Code
<div class="elementbox">
<label class="form-label">Content<span class="required">*</span></label>
<div class="controls">
<textarea name="content_body" id="content_body" rows="10" cols="80"><?php echo $content_body; ?></textarea>
</div>
</div>
<script>
var url = "<?php echo base_url(); ?>";
CKEDITOR.replace( 'content_body',{
//extraPlugins: 'imageuploader'
} );
</script>
My Jquery validation code
$("#add_content_pages").validate({
ignore: [],
debug: false,
rules: {
title: {
required: true
},
content_id: {
required: true
},
content_body:{
required: function()
{
CKEDITOR.instances.content_body.updateElement();
}
}
},
messages: {
title: {
required: "Please enter Title"
},
content_id: {
required: "Please Select Content Type"
},
content_body: {
required: "Please enter Content"
}
},
errorPlacement: function (error, element) {
var attr_name = element.attr('name');
if (attr_name == 'type') {
error.appendTo('.type_err');
} else {
error.insertAfter(element);
}
}
});
Any Solution what I am missing?
please check this code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js"></script>
<script src="https://cdn.ckeditor.com/4.6.2/standard/ckeditor.js"></script>
then html form
<form action="" method="post" id="check_form">
<div class="elementbox">
<label class="form-label">Content<span class="required">*</span></label>
<div class="controls">
<textarea name="content_body" id="content_body" rows="10" cols="80"></textarea>
<div id="error_check_editor"></div>
</div>
</div>
<script>
CKEDITOR.replace('content_body');
</script>
<br/>
<input name="submit" type="submit" value="Submit" class="button" id="submit"/>
</form>
then script
<script>
$.validator.addMethod("check_ck_add_method",
function (value, element) {
return check_ck_editor();
});
function check_ck_editor() {
if (CKEDITOR.instances.content_body.getData() == '') {
return false;
}
else {
$("#error_check_editor").empty();
return true;
}
}
$(document).ready(function () {
$("#check_form").validate(
{
ignore: [],
debug: false,
errorPlacement: function (error, element) {
if (element.attr("name") == "content_body") {
error.insertAfter(element);
}
},
rules: {
content_body: {
check_ck_add_method: true
}
},
messages: {
content_body: {}
}
});
});
</script>
Html code
<form id="cekform">
<input class="cek" name="cek[1]" type="checkbox" value="1">
<input class="cek" name="cek[2]" type="checkbox" value="2">
<input class="cek" name="cek[3]" type="checkbox" value="3">
</form>
js code
<script type="text/javascript">
$(document).ready(function() {
$("#cekform").validate({});
$('.cek.true').each(function() {
$(this).rules('add', {
required: true,
number: true,
max:2,
messages: {
required: "your custom message",
number: "your custom message",
max: "your custom message"
}
});
});
});
</script>
this js to make change class input
$('input[class^="cek"]').click(function() {
var val = $(this).val();
if ($(this).is(':checked')) {
$(this).addClass('true');
} else {
$(this).removeClass('true');
}
});
i want validate only input which had checked, but when itray my code validation didnt work
can anyone help me ?
I am a bit of a noob with jQuery and am learning for Uni.
I am working on a HTML web site with an associated HTML mobile application that I will compile in phonegap build.
I have a HTML form that I want to include on both the site and the app which I have coded and is successfully validating with jQuery. I would also like to post the form data with jQuery but am struggling to find how best to achieve this.
My form looks like this
<form action="http://myaddress.com/process.php" method="post" name="jform" id="jform">
<div>
<label for="name"><b>Name:</b></label><br>
<input type="text" name="name" id="name">
</div>
<div>
<label for="dob"><b>Date of Birth:</b></label><br>
<input type="text" name="dob" id="dob">
</div>
<div>
<label for="visit"><b>Date of Visit:</b></label><br>
<input type="text" name="visit" id="visit">
</div>
<div class="labelBlock">
<b>Favourite Exhibit:</b>
<div class="indent">
<input type="radio" name="fave" id="exhibit1" value="Exhibit1">
<label for="exhibit1">Exhibit 1</label><br>
<input type="radio" name="fave" id="exhibit2" value="Exhibit2">
<label for="exhibit2">Exhibit 2</label><br>
<input type="radio" name="fave" id="exhibit3" value="Exhibit3">
<label for="exhibit3">Exhibit 3</label>
</div>
</div>
<div>
<label for="comment"><b>Comments:</b></label><br>
<textarea name="comment" id="comment" rows="10" cols="40" draggable="false"></textarea>
</div>
<div id="center-button">
<input name="submit" type="submit" id="submit" value="Submit" class="center-text">
</div>
</form>
My validation script looks like this:
<script>
$(document).ready(function() {
$('#jform').validate({
rules: {
name: "required",
dob: "required",
visit: "required",
fave: "required",
comment: "required"
}, //end rules
messages: {
name: {
required: "Please tell us your name"
},
dob: {
required: 'Please select your Date of Birth'
},
visit: {
required: 'Please select the date you visited'
},
fave: {
required: 'Please select your favourite exhibit'
},
comment: {
required: 'Please tell us about your visit'
}
},//end messages
errorPlacement: function(error, element) {
if ( element.is(":radio") ) {
error.appendTo( element.parent());
} else {
error.insertAfter(element);
}
}
}); // end validate
submitHandler: function(form) { //This is the submit handler.
var name = $('#name').val();
var dob = $('#dob').val();
var visit = $('#visit').val();
var fave = $("input[name='fave']:radio:checked").val();
var comment = $('#comment').val();
$.ajax({
type: 'POST',
url: 'process-post.php',
data: {name:name, dob:dob, visit:visit, fave:fave, comment:comment},
success: function(data1){
if (data1 == 'success') {
window.location.href = 'index.html';
}
else {
alert('Oops! It looks like something has gone wrong. Please try again.');
}
}
});
}}); // end ready
I really am struggling with this so would appreciate any help.
My PHP Looks like this
<?php # PROCESS JOURNAL ENTRY.
# Check form submitted.
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
# Open database connection.
require ( '../connect_db.php' ) ;
# Execute inserting into 'forum' database table.
$q = "INSERT INTO journal(name,dob,visit,fave,comment,date)
VALUES ('{$_POST[name]}','{$_POST[dob]}','{$_POST[visit]}','{$_POST[fave]}','{$_POST [comment]}',NOW() )";
$r = mysqli_query ( $dbc, $q ) ;
# Report error on failure.
if (mysqli_affected_rows($dbc) != 1) { die ('Error' . mysqli_error($dbc)); } else { echo "success"; }
# Close database connection.
mysqli_close( $dbc ) ;
}
?>
Yes he is correct jquery's ajax will accomplish this or http post. You will use one of the mentioned methods to get the data from the HTML form and send it to the sever.
You will need jQuery ajax. This is a very powerful function that is used any time jQuery validation is used. It also lets you submit to the PHP file and get the results without refreshing the page.
EDIT:
Depending on the complexity of your project, ajax may be overkill. You can just normally submit the form after it is validated like this:
<script>
$(document).ready(function() {
$('#jform').validate({
rules: {
name: "required",
dob: "required",
visit: "required",
fave: "required",
comment: "required"
}, //end rules
messages: {
name: {
required: "Please tell us your name"
},
dob: {
required: 'Please select your Date of Birth'
},
visit: {
required: 'Please select the date you visited'
},
fave: {
required: 'Please select your favourite exhibit'
},
comment: {
required: 'Please tell us about your visit'
}
},//end messages
errorPlacement: function(error, element) {
if ( element.is(":radio") ) {
error.appendTo( element.parent());
} else {
error.insertAfter(element);
}
}
}); // end validate
submitHandler: function(form) { //This is the submit handler.
$(form).submit();
}
}); // end ready
</script>
Here is the part that I add:
submitHandler: function(form) { //This is the submit handler.
$(form).submit();
}
This will submit a form normally, meaning that it will run the PHP script and then refresh the page.
If you decide you want to use ajax, you can just replace $(form).submit(); with this:
var name = $('#name').val();
var dob= $('#dob').val();
var visit = $('#visit').val();
var fave = $("input[type='radio'][name='fave']:checked").val();
var comment = $('#comment').val();
$.ajax({
type: 'POST',
url: 'http://myaddress.com/process.php',
data: {name:name, dob:dob, visit:visit, fave:fave, comment:comment},
success: function(data){
if (data == 'success') {
//do something
}
else {
//do something
}
}
});
The data that I am using in the success portion of the function is the value returned from the PHP script. Since you mentioned comments, I am assuming that you PHP is not returning data, but more or less a completion message. In that case, you would just have your PHP echo 'success'; if it was successful. Then fill in the "do somethings" in the jQuery.
I have a simple search form using HTML, PHP, and jQuery but the form submits even though some fields are empty and the validator warnings appear for a moment. So I would submit the form, the warnings about "Required field" appear, and it submits anyway. The validator is being triggered but isn't stopping the form.
HTML + PHP
<form action="dater.php" method="post" id="daterange">
<table width = "1000px">
<col width="250px" />
<col width="250px" />
<col width="250px" />
<col width="250px" />
<tr>
<? dateRangeView(); ?>
<td><input class="comment" type="text" name="groups" id="groupname" placeholder="Enter group name"> *</td>
<td><input class="comment" type="text" name="employee" id="staffname" placeholder="Enter employee name"> *</td>
</tr></table>
*Leave these blank to view all<br>
<button class="mainButton" id="viewTimesheets" value="viewTimesheets" type="submit">View</button>
function dateRangeView()
{
$query = "SELECT DISTINCT weekending FROM payroll_ts ORDER BY weeke DESC";
$result = mysql_query($query);
echo'<td><select id="startdate" class="infotable" name="startdate"><option value="">---- Start date ----</option>';
while ($row = mysql_fetch_array($result))
{
echo'<option value="'.$row{'weeke'}.'">'.$row{'weeke'}.'</option>';
}
echo'</select><br><td><select id="enddate" class="infotable" name="enddate"> <option value="">---- End date ----</option>';
$query = "SELECT DISTINCT weekending FROM payroll_ts ORDER BY weeke DESC";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result))
{
echo'<option value="'.$row{'weeke'}.'">'.$row{'weeke'}.'</option>';
}
echo'</select><br></td>';
}
VALIDATOR PLUGIN CODE
<script language="javascript" type="text/javascript">
/*-------------Validator-------------*/
$.validator.setDefaults({
submitHandler: function() { alert("submitted!");
form.submit();}
});
$(function() {
$("#daterange").validate({
rules: {
startdate: "required",
enddate: "required"
},
messages: {
startdate: "required",
enddate: "required"
}
});
});
</script>
I've been at it for four hours now, used .on(), return false; onSubmit() and e.preventDefault(); although I may have gotten the syntax on those messed up... This is the plugin I'm using... http://jqueryvalidation.org/validate/
Try this.
$(document).ready(function () {
$.validator.setDefaults({
submitHandler: function (form) {
alert('submitted');
form.submit();
}
});
$('#daterange').validate({
rules: {
startdate: {
required: true
},
enddate: {
required: true
}
}
});
});
Working JsFiddle example Demo
Hope this helps, Thank you
or here is the code for you both works
$(document).ready(function () {
$.validator.setDefaults({
submitHandler: function() { alert("submitted!");
form.submit();}
});
$(function() {
$("#daterange").validate({
rules: {
startdate: "required",
enddate: "required"
},
messages: {
startdate: "required",
enddate: "required"
}
});
});
});
$(document).ready(function () {
$("#daterange").validate({
rules: {
startdate: "required",
enddate: "required"
},
messages: {
startdate: "required",
enddate: "required"
}
});
if($("#daterange").valid()) {
// call your function;
alert("submitted!");
}
});
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."); ?>',
}