I want to display one error message at the top, if validation fails. I don't want to use errorPlacement option. Instead I want to show the message in the Bootstrap alert.
Here is my HTML:
<form method="POST" action="/role" accept-charset="UTF-8" id="roles_form">
<div class="alert alert-danger vd_hidden">
<span class="vd_alert-icon"><i class="fa fa-exclamation-circle vd_red"></i></span>
Please select a role.
</div>
<input id="role_administrator" name="role" type="radio" value="administrator">
<label for="role_administrator">Administrator</label>
<input id="role_manager" name="role" type="radio" value="manager">
<label for="role_manager">Manager</label>
<input type="submit" value="Submit">
</form>
Here is my JavScript:
var roles_form = $('#roles_form');
var error_roles_form = $('.alert-danger', roles_form);
roles_form.validate({
focusInvalid: false, // do not focus the last invalid input
debug: true,
rules: {
role: "required"
},
invalidHandler: function (event, validator) { //display error alert on form submit
error_roles_form.fadeIn(500);
},
});
This does not work. Neither it does any validation (form gets submitted, if I remove the debug option) nor does it show any error.
Update:
After looking at the solution provided by Sparky, I realised that I am using a plugin to hide radio elements and replace with a style-able object. As the radio elements were hidden, jQuery Validation failed to validate them properly with my JavaScript code. What surprised me is that it did not show any JavaScript error, even with debug mode on.
Quote OP:
"This does not work. Neither does any validation (form gets submitted, if I remove the debug option) nor [does] it shows any error."
Actually, the code you posted is working: http://jsfiddle.net/TTJB7/
Quote OP:
"I want to display one error message at the top, if validation fails. I don't want to use errorPlacement option."
For placing the error message into a box, you'll need the errorLabelContainer option. So instead of the default behavior of putting error messages next to each input (errorPlacement), the errorLabelContainer will put the messages into one specified container that is hidden/shown automatically.
var roles_form = $('#roles_form');
var error_roles_form = $('.alert-danger', roles_form);
roles_form.validate({
focusInvalid: false, // do not focus the last invalid input
debug: true,
rules: {
role: "required"
},
messages: {
role: "Please select a role."
},
errorLabelContainer: error_roles_form // puts the error messages into this container
});
HTML:
<form id="roles_form">
<div class="alert alert-danger vd_hidden"></div>
<input id="role_administrator" name="role" type="radio" value="administrator" />
<input id="role_manager" name="role" type="radio" value="manager" />
<input type="submit" value="Submit" />
</form>
DEMO: http://jsfiddle.net/TTJB7/1/
For all other available callback options, see the documentation.
When I realised that the actual problem is with the hidden radio elements, I did a little research and solved the issue.
First I applied ignore to "" so that it will not ignore hidden elements and validate them.
Then I need to stop default error message to appear after the element. So I assigned an empty function to that option.
Here is my final JavaScript code:
roles_form.validate({
focusInvalid: false, // do not focus the last invalid input
ignore: "",
rules: {
role: "required"
},
invalidHandler: function (event, validator) { //display error alert on form submit
error_roles_form.fadeIn(500);
},
errorPlacement: function(error, element) {}
});
Related
I have found different answers to similar questions, but not to this one.
I want to make sure that the user selects something from a dropdown list, like in my code:
<div class="form-group">
<label for="title">Provincia:</label>
<i class="icon-append fa fa-user"></i>
<div>
<form:select path="provincia" id="provincia" name="provincia">
<form:option value="" label="Seleccionar Provincia" />
<form:options items="${provincia}" value="${provincia.id_provincia}" selected="${selected}"></form:options>
</form:select>
</div>
</div>
I would like it to be in the browser, not in the server.
PD: When I use required in HTML (select name="somename" required) or (class="required"), it doesnot work.
- The Javascript solutions that I have found does not work either.
Thanks
Here is some code that I am currently using for one of my projects. SupplierType is a dropdown and so is SupplierPremium, however; that dropdown is conditionally required. Keep an eye on your console window to ensure JQueryValidation is properly installed.
//Start Validation
$("#AddSupplier").validate({
errorClass: 'errors',
rules: {
SupplierName: {
required: true,
email: false
},
SupplierType: {
required: true
},
SupplierPremium: {
required: function (element) { return $("#SupplierType").val() == 'Auction'; }
}
},
messages: {
SupplierType: { required: "Please select a supplier type" }
}
});
Take a look at the JQuery validation plugin. This is completely client side, user friendly and can be used for a variety of different situations. Jquery Validation Plugin
How to validate input fields inside a modal popup using ParsleyJS?
I have already an error container in layout page which works for page level input fields. I want to validate input fields in a modal popup and the error message should also be displayed in the popup.
To display validation errors inside a specific the Modal, you will need to use this data attribute on the input elements:
data-parsley-errors-container="#modal_div_error_container"
This is how you can validate the input fields inside your Modal <div>
JS:
$(function(){
var parsley_valiation_options = {
//errorsWrapper: '',
errorTemplate: '<span class="error-msg"></span>',
errorClass: 'error',
}
//check if modal_div element exists on the page
if ($('#modal_div').length > 0) {
//Attach Parsley validation to the modal input elements
$('#modal_div input').parsley(parsley_valiation_options);
//On modal submit button click, validate all the input fields
$('#modal_div_submit_button').click(function(event) {
event.preventDefault();
var isValid = true;
$('#modal_div input').each(function(){
if($(this).parsley().validate() !== true)
isValid = false;
})
if(isValid) {
alert("All fields are validated !");
}
});
}
});
HTML:
<!-- Modal -->
<div id="modal_div">
<!-- Modal div error container (Validation error messages will display here)-->
<div id="modal_div_error_container"></div>
<label for="name">
Name (should be alphanumeric and min length: 7)
</label>
<input type="text" id="name" name="name" data-parsley-minlength="7" data-parsley-minlength-message="Name must be at least 7 characters" data-parsley-required="true" data-parsley-errors-container="#modal_div_error_container"/>
<button type="submit" id="modal_div_submit_button">Submit</button>
</div>
You need to use button type as a "submit" instead of "button". Then that might solve your issue.
I want to use an onlick event handler to validate some form fields using jquery Validate. To do this I have the following code:
<input type="text" id="Name" name="Name">
<a class="btn btn-primary js-add-names" href="#">Add Names</a>
<input type="text" id="Age" name="Age">
<a class="btn btn-primary js-add-ages" href="#">Add Age</a>
<script>
$(".js-add-names").click(function (e) {
e.preventDefault();
$("form").validate({
rules: {
Name: {
required: true
}
},
messages: {
Name: "The Name is required"
}
});
if (!$("form").valid()) {
return;
}
// otherwise do stuff but we dont want to submit form
});
$(".js-add-ages").click(function (e) {
e.preventDefault();
$("form").validate({
rules: {
Age: {
required: true
}
},
messages: {
Age: "The Age is required"
}
});
if (!$("form").valid()) {
return;
}
// otherwise do stuff but we dont want to submit form
});
</script>
What I've noticed is that only one event handler works out the two based on whichever one was clicked first i.e. if I click the button with class js-add-names, the validation for that handler works as expected.
Now If I click the button with class js-add-ages having previously clicked js-add-names then the handler for js-add-age doesn't work and vis versa?
Any ideas why this is happening and what is the fix?
* UPDATE *
Further to suggestion by Sparky I have re-written the code as below but now when I click js-add-names, the validation for that handler works as expected
Now If I click the button with class js-add-ages having previously clicked js-add-names then the handler for js-add-age doesn't work becuase the validation has previously added a rule for input #Name. How do I reset the form or remove the rules each time the event handlers fire?
<form>
<input type="text" id="Name" name="Name">
<a class="btn btn-primary js-add-names" href="#">Add Names</a>
<input type="text" id="Age" name="Age">
<a class="btn btn-primary js-add-ages" href="#">Add Age</a>
// other inputs
<input type="checkbox" name="CarOwner" value="Yes"> Car owner
<input type="submit" value="Submit">
</form>
<script>
$("form").validate();
$(".js-add-names").click(function (e) {
e.preventDefault();
$("#Age").rules("remove");
$("#Name").rules("add", {
required: true,
messages: {
required: "The Name is required"
}
});
if (!$("form").valid()) {
return;
}
// otherwise do stuff but we dont want to submit form
// ...
//Reset input field
$("#Name").val('');
});
$(".js-add-ages").click(function (e) {
e.preventDefault();
$("#Name").rules("remove");
$("#Age").rules("add", {
required: true,
messages: {
required: "The Age is required"
}
});
if (!$("form").valid()) {
return;
}
// otherwise do stuff but we dont want to submit form
// ...
//Reset input field
$("#Age").val('');
});
</script>
Any ideas why this is happening and what is the fix?
The .validate() method is only used for initializing the plugin on your form and therefore should only be called once when the page is loaded. Subsequent calls are always ignored. So when you use one click handler, you initialize the validate plugin, and the other call to .validate() in the other click handler will do nothing.
The fix...
Call .validate() ONE time to initialize the plugin on your form.
Do NOT call .validate() from a click handler since this is not the testing method; it's only the initialization method.
Use the plugin's built-in submitHandler and invalidHandler functions for stuff you need to do when the form is valid and invalid.
Since you appear to be using your click handlers to add fields/rules to an existing form, then use the .rules('add') and .rules('remove') methods to add and remove any rules dynamically.
I'm using jQuery validation to generate a custom message if validation fails.
By default, the message is going to the right of the input field that it's validating.
I want this message to instead always go to the right of the field title.
For example, I want it to look like this:
http://jsfiddle.net/zWgbP/
I've played around with adding:
errorPlacement: function (error, element) {
error.insertBefore(element);
},
...but that isn't quite right since I need it to come before the break after the title "Last Name".
Is there a better way to target the field title if I surround it in a span or div and give it an id using the jQuery method I have below?
If not, is there a better method?
THE JAVASCRIPT
$(document).ready(function() {
// validate signup form on keyup and submit
$("#newform").validate(
rules: {
lastname: {
required: true,
minlength: 2
},
messages: {
lastname: {
required: "* please fix",
minlength: "* please fix"
},
THE HTML
<form name="newform" id="newform" method="post" onsubmit="return OnNewButton();">
<input type='text' id='lastname' name='lastname' size='20' value = "" />
</form>
THE CSS
<style type="text/css">
#newform label.error {
color: red;
font-size: 15px;
}
</style>
The answer was to add the following errorPlacment option in my jQuery:
errorPlacement: function(error, element) {
error.appendTo('#title-' + element.attr('id'));
},
I then changed this:
Last Name<br />
into
<span id="title-lastname">Last Name</span><br />
The id of the filed being validated is "lastname".
Doing this appended my error message to the span before the break br perfectly.
Thanks for you help everybody.
I am using jquery validation plugin and zend framework. I have my form in a table. I am displaying an image as an error when a textfield is not validated. The error image is displayed very next to textbox in the same td of table. But I want to show error message/image in next td of same tr.
For example this is before submit:
<table><tr><td>First Name</td><td><input type="text" class="required" /></td><td></td></tr></table>
I want this after submit with empty field:
<table><tr><td>First Name</td><td><input type="text" class="required" /></td><td><img id='exclamation' src='images/exclamation.gif' title='This field is required.' /></td></tr></table>
I am using this js function for now:
$(obj).find("input.required").each(function(){
$(this).rules("add", {
required: true,
minlength: 2,
messages: {
required : "<img id='exclamation' src='images/exclamation.gif' title='This field is required.' />",
minlength: "<img id='exclamation' src='images/exclamation.gif' title='At least 2 characters.' />"
}
});
});
After a time I got my answer. Infact I want to display an image with a callout(containing error) in next column(td) of input field that is not validated by validation plugin. And when an input field is validated, this error image should be removed with its callout on it.
Here is my solution.
$("form").validate({
errorPlacement: function(error, element) {
//There should be an error
if(error.html() != ''){
element.parent().next().html("<img id='exclamation' src='images/exclamation.gif' />").callout({
width : 200,
cornerRadius : 8,
className : "validationCallout",
content : error,
align : "left",
nudgeHorizontal : -14,
nudgeVertical : 4,
arrowHeight : 6
});
}
},
success: function( label ) {
$(obj).find(".valid").parent().next().html(""); //remove error image from next column(td) of input containing "valid" class
$(obj).find(".valid").parent().next().closeCallout(); //remove callout on error image from next column(td) of input containing "valid" class
}
});
This code may be complex but it is working for me now. A callout plugin is used here that is not related to the question but may help anyother.
Can anyone make it more simple?