jQuery validate display error message in div - javascript

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>

Related

Jquery Validation For checkbox with index

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.

Set jquery selector dynamically based on HTML form ID value

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

Adding own rule in jquery validation plugin

I have next jquery code:
$("input").rules("add", {
required: true,
messages: {
required: 'Please enter your telephone number'
},
errorPlacement: function(error, element) {
console.log('bob');
element.insertBefore(error);
}
});
I am trying to add new rule like in answer in this question : jquery validation & id's ft numbers
I have such html code:
<form method='post' action='' id='#countersForm'>
<input id="88" class="counter_input active" type="text" enabled="">
<input id="89" class="counter_input active" type="text" enabled="">
</form>
My problems are:
1) Why browser tries to validate field on page loaded? I don't need this (message bob appeaing on page load.
2) Why only first input field is validating? I want to validate all fields.
3) Why console says , that element is not defined?
documentation says that element parameter contain validated element. console.log(element) says that it is undefiened. Why?
From documentation:
Read, add and remove rules for an element.
it says 'an' element. $('input') in your case returns two elements.
validation plugin uses name attribute of elements, your element's doesn't have names.
You have to initialize the plugin using validate() method on the form you want to validate, for e.g.
$("#myform").validate({ //where my form is the id of your form
rules: {
name: "required", //name is the name of your element
},
messages: {
}
});
Thanks for your answers and comments.
I solved my problem. Working code (current problem is solved) is here: http://jsfiddle.net/2LRv7/2/
There was a huge mistake in my js code. I put errorPlacement section to the rules function. I have to put this option to .validate section.
$("#countersForm").validate({
errorPlacement: function (error, element) {
console.log(error);
var br = $( "<br>" );
error.insertAfter(element);
br.insertAfter(element);
}
});
Also, as #TilwinJoy said, I used $('input').rules(/*....*/) wrong. I had to use each function.
This code is okay:
$("input").each(function () { // next code will affect all input fields
$(this).rules("add", { // $(this) is my input field
required: true,
digits: true,
messages: {
required: 'Это поле обязательно для заполнения',
digits: 'В поле могут быть только цифры'
}
});
});
Current problem solved, but I have another. If you want to help check this question: Class is not being added to the error element on first check , but when field is being checked again all going ok (jquery validation plugin)

Trying to write a jquerying script that uses a submit function to validate two fields

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.

jQuery validation plugin. Validation for non form fields?

Ні, 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');
};
});
});

Categories

Resources