How to get Only one custom jquery validation message and that to in a <div> above element if checkbox name is array with index.
<div class="error">Error will show here</div>
<input type="checkbox" value="0" name="is_appraisal[0]" class="is_appraisal_f siblingcheckbox" id="is_appraisal_f">
<input type="checkbox" value="0" name="is_appraisal[1]" class="is_appraisal_s siblingcheckbox" id="is_appraisal_s">
I tried this but it is not working
$.validator.addMethod("onechecked", function (value, elem, param) {
if ($(".siblingcheckbox:checkbox:checked").length > 0) {
return true;
} else {
return false;
}
}, "Please select any one of the following!");
$.validator.addClassRules("siblingcheckbox", {
onechecked: true
});
Validation is working but this gives error message below both checkbox.Any Help ?
if you want all your jQuery Validate error messages to appear in one place you would use.http://docs.jquery.com/Plugins/Validation/validate#toptions Find errorPlacement option on that page.
1)
if you want custom placement for all of your errors you can do this:
$("#myform").validate({
errorPlacement: function(error, element) {
error.appendTo('#errordiv');
}
});
2)
If you want to specify specific locations for one or multiple error labels you can do this.
errorPlacement: function(error, element) {
if (element.attr("name") == "email" )
error.insertAfter(".some-class");
else if (element.attr("name") == "phone" )
error.insertAfter(".some-other-class");
else
error.insertAfter(element);
}
Edit
This bellow code add in your validation function
$("#YOURFORMID").validate({
errorPlacement: function(error, element) {
error.appendTo('.error');
},
success: function(label,element) {
$('.error').html('');
}
});
NOTE:: name of checkbox is different(is_appraisal[0],is_appraisal[1]) so message will display two time.
Also check bellow snippet working demo for group of checkbox
validation with custom message set at custom place
$(document).ready(function(){
$("#myform").validate({
rules: {
"is_appraisal[]": "required",
},
messages: {
"is_appraisal[]": "Please select any one of the following!",
},
errorPlacement: function(error, element) {
error.appendTo('.error');
}
});
});
.error
{
color:red;
}
<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.15.0/jquery.validate.min.js"></script>
<div class="error"></div>
<form name="myform" id="myform" action="" method="post">
<input type="checkbox" value="0" name="is_appraisal[]" class="is_appraisal_f siblingcheckbox" id="is_appraisal_f">
<input type="checkbox" value="0" name="is_appraisal[]" class="is_appraisal_s siblingcheckbox" id="is_appraisal_s">
<input type="submit" >
</form>
Demo link https://jsfiddle.net/9q0jwxo6/1/
Jquery validation library generates a label for each invalid html element like:
<label id="email_id-error" class="error" for="email_id">Please enter your Email.</label>
Just copy this label from html dom and remove its error message and put it on place where you want the error message. Now the error message placement is where this label is.
Related
I have several forms on one page that differ based on the forms' IDs. The ID's differ by an appended _0, _1, _2 etc (an index value created by a rails each do loop).
I'm trying to validate these forms, however to keep my code DRY, I'd like the form selector to be dynamic. I need to somehow grab the form's ID value ("_0") and add it to the jQuery selector.
This Fiddle gives an exmaple of how I'm tackling the problem now.
The code inside of the validation() block is the same between the jQuery functions. I need to set the selector variable to something like this:
$("new_loan_question_answer_"+i)
I'm not sure how to pass the _0 or _1 form the HTML form to the jQuery function.
form html
<div class="form">
<p>Question #1 text</p>
<form id="question_response_0">
<input type="text" name="response"></input>
<input type="submit">
</form>
</div>
<div class="form">
<p>Question #2 text</p>
<form id="question_response_1">
<input type="text" name="response"></input>
<input type="submit">
</form>
</div>
jquery
$(function () {
$("#question_response_0").validate({
rules: {
"response": {
required: true
}
},
messages: {
"response": {
required: 'This field is required'
}
},
errorPlacement: function (error, element) {
error.insertAfter(element.parent());
}
});
});
$(function () {
$("#question_response_1").validate({
rules: {
"response": {
required: true
}
},
messages: {
"response": {
required: 'This field is required'
}
},
errorPlacement: function (error, element) {
error.insertAfter(element.parent());
}
});
});
Don't bother with incremental id attributes. It becomes a pain to maintain and leads to issues keeping code DRY. This kind of thing is exactly what classes were invented for:
<div class="form">
<p>Question #1 text</p>
<form class="question_response"> <!-- < use a common class on the form -->
<input type="text" name="response"></input>
<input type="submit">
</form>
</div>
<div class="form">
<p>Question #2 text</p>
<form class="question_response"> <!-- < use a common class on the form -->
<input type="text" name="response"></input>
<input type="submit">
</form>
</div>
Now you only need to attach validate to the .question_response class. Unfortunately it seems that the error highlighting (and possibly other features) is bugged in the validate plugin when instantiating on a selector that contains multiple form elements, so you need to loop through each form in turn:
$(function () {
$('.question_response').each(function() {
$(this).validate({
rules: {
"response": {
required: true
}
},
messages: {
"response": {
required: 'This field is required'
}
},
errorPlacement: function (error, element) {
error.insertAfter(element.parent());
}
});
});
});
Example fiddle
Check out http://api.jquery.com/submit/ for example.
If you use an event handler to call a function, then the event may contain the information you need (ID of submitted form).
Information regarding the event object is available here: http://api.jquery.com/category/events/event-object/
Could use the classes shown already in your markup, or add a class to form tags:
$('div.form form').validate({/* options*/}) ;
This will include all forms that match the selector and each will have it's own validation instance
I am new with jQuery validation and learing so I don't have any idea about this. Now I am using jQuery Validate plugin and want to display error message inside div element. I have created div for every error message.
For example I have Name input field and want to display error message inside nameError div.
<div>
<label for="name">Name</label>
<input id='name' name="name" value="" />
</div>
<div id="nameError">
<!-- Display Name Error Here -->
</div>
Is it possible for jQuery Validation Plugin? I have no idea that why I am posting here to get help from you.
MY JQUERY CODE IS:
$(function () {
$.validator.addMethod("regex", function (value, element, regexpr) {
return regexpr.test(value);
}, "Please enter a valid name.");
$("#myForm").validate({
rules: {
name: {
required: true,
regex: /^[A-Za-z]+$/
}
}
});
});
MY JSFIIDLE
Thanks.
Here's a quick sample: http://jsfiddle.net/4PuJL/7/
jQuery.validator.setDefaults({
errorPlacement: function(error, element) {
error.appendTo('#nameError');
}
});
You may add a check in errorPlacement handler like below:
Please note that errorPlacement function is called for each error, if you need more handling on error message, please check for invalidHandler
jQuery.validator.setDefaults({
errorPlacement: function(error, element) {
if (element.attr("name") == "name" ) //Id of input field
error.appendTo('#nameError');
if (element.attr("name") == "anotherInputField" ) //Id of input field
error.appendTo('#anotherInputFieldError');
}
});
check the following link
My Fiddle
HTML :
<form>
<input type="text" required pattern="/^[A-Za-z]+$/" >
<input type="submit" value="search">
</form>
I have a form which is being validated using Jquery Validate.The form contains 2 checkboxes with the same name, of which at least one has to be selected. To accomplish this, i am using the .validate() on the checkboxes name , along with the rule :required".
While i am able to validate successfully, (i.e error messages pop up when no checkboxes are selected), the error messages are being displayed after the first checkbox, which disrupsts my formatting.
I am currently using errorElement and errorPlacement to make the error messages show up in a pair of span tags after each input element, but it seems to be not applying to the checkboxes.
HTML(Extract) :
<form id='BizAddItem' name='BizAddItem' method='post' action='additemprocess.php' enctype='multipart/form-data' novalidate='novalidate'>
//More input elements above
<div class='BizAddItemDetails'>
<label for='BizFulfilment'>Order Fulfilment:</label>
<input type='checkbox' id='BizFulfilment' name='BizFulfilment[]'>Delivery  
<input type='checkbox' id='BizFulfilment' name='BizFulfilment[]'>In-Store Pickup
<span></span>
</div>
//More input elements below
</form>
jQuery code (Extract):
$('#BizAddItem').validate({
errorElement:"span",
errorPlacement:function(error,element){
error.insertAfter(element);
},
rules:{
//More items above
'BizFulfilment[]':{
required:true
},
},
messages:{
//More items above
'BizFulfilment[]':{
required:"Please select at least one option"
},
},
submitHandler:function(form){
form.submit();
}
})
Any help rendered would be appreciated. Thanks!
Try this....
errorPlacement:function(error, element)
{
if($(element).attr("name")=="BizFulfilment[]")
{
$(element).parent().append(error);
}else
{
$(error).insertAfter(element);
}
},
I'm trying to meet the following objectives but having problems with my code to get it to work. Any help would be grateful.
Objective: Add javascript/jQuery code to require a login. Have 2 fields, First Name and Last Name. Validate entry. Must be "Rick" and "James" respectively. Once fields are validated, have a picture appear on the page. When you click the picture, have the page content display. Have at least 2 link buttons with rollover states to change button color and/or text size.
Here is my script:
$(document).ready(function() {
$("#signup").validate({
rules: {
firstName: { required: true },
lastName: { required: true }
}, //end rules
messages: {
firstName: {required: "You must enter a value in this field." },
lastName: {required: "You must enter a value in this field." }
}, // end messages
errorPlacement: function(error, element) {
error.insertAfter(element);
}
}); // end validate
$('#signup').submit(function() {
if (($('#firstname').val() == 'John') && ($('#lastname').val() == 'Taylor'))
{alert('This works!');
$('#pic').show();
$('#main').css("backgorund-image", "url(starwars.jpg)");
}
else { alert('Invalid Name'); }
}); //end submit
$('#pic').click(function() {
$('#button1').show();
$('#button2').show();
}); // end click
}); // end ready
HTML:
<form id="signup">
<div>
<label for="firstName" class="label">First Name</label>
<input name="firstName" type="text" id="firstname" class="required" title="Please type your first name.">
</div>
<div>
<label for="lastName" class="label">Last Name</label>
<input name="lastName" type="test" class="required" id="lastname">
</div>
<div>
<input type="submit" name="submit" id="submit" value="Submit">
</div>
<div>
<img src="sith_ewok.png" id="pic">
<button id="button1">Jedi</button>
<button id="button2">Sith</button>
</div>
</form>
The only error that stands out so far in your code is spelling background-image incorrectly in the submit function.
The one thing that seems likely is that you would see minimal effects from clicking the submit button because of the form automatically posting. That will likely mean that you never see the effects of your script being executed. To fix that, add return false; to the submit processing:
$('#signup').submit(function() {
if (($('#firstname').val() == 'John') && ($('#lastname').val() == 'Taylor'))
{alert('This works!');
$('#pic').show();
$('#main').css("backgorund-image", "url(starwars.jpg)");
}
else { alert('Invalid Name'); }
return false;
}); //end submit
Note that if you are actually going to use this form to do further processing on another page, you might later want to have the submit function allow the page to post in the case that the fields check out. To do that, move the return false; line of code into the else and/or add a return true; as the last line in the main if block.
Make up your mind! Is it "Rick James" or 'John Taylor' ?!
Anyways, the code looks alright except
your should put return false; in $.submit() to prevent page
refreshing
spelling errors on background-color
image and two buttons should be set to display:none at beginning, so the show() function will actually works
Also I do not see your code for changing button color/state anywhere. So I just added some .mouseover and .mouseout events on the buttons. This is normaly can be done with just css such as button:hover {color:red}.
Here is a working demo: http://jsfiddle.net/dUG8Y/
Hope it helps, and may the Force be with you.
Ні, all!
I have a little question about jQuery.Validation plugin: - Can I complete validation for input fields that are not form fields (i.e no in the "form" tag) using jQuery.Validation plugin?
Thanks.
Yes you can, but the field still needs to be inside a set of <form> tags. However, you do not need to "submit" this form in order to check validation on the field(s) inside. You use the .valid() method to check this form independently of form submission.
http://jsfiddle.net/9fgVN/13/
<form id="myNonsubmitForm" action="#">
<textarea name="comments" id="comments" rows="5" cols="30"></textarea>
</form>
<button id="myButton">Click to Check Validation Status</button>
<input type="text" id="output" />
$(document).ready(function() {
$("#myNonsubmitForm").validate({
validClass: 'valid', // as per your configuration
rules: { // set rules as per your configuration
comments: {
required: false,
maxlength: 10
}
},
errorPlacement: function(error, element) {
// use this to control placement of error messages
// removal of errorPlacement handler will result in message appearing next to field automatically.
}
});
$("#myButton").click(function() { // validate on button click for this example
if($("#myNonsubmitForm").valid()){
$('#output').val('passed');
} else {
$('#output').val('failed');
};
});
});