I want to display a parsley message in an else clause of my javascript code:
if ( ...is valid ) {
//do things
} else {
//display parsley error
}
I know that Parsley allows custom validators as documented here: http://parsleyjs.org/documentation.html#javascript
But I merely want to display the message until the field is modified. I could create a validator such as:
$( '#myInput' ).parsley( {
validators: {
alwaysFalse: function ( val ) {
return false;
}
}
, messages: {
myMessage: "Form is invalid"
}
});
But then how would I trigger this and only this validator? (There is another validator already attached)
your messages object should be a mirror of your validators object but with the messages to display.
messages: {
alwaysFalse: "Form is invalid"
}
and you could try
validators: {
alwaysFalse: function(val){
return false;
},
required: function ( val ) {
return false;
}
}
also
Warning : you must remove parsley-validate auto-binding code in your forms DOM to allow you to override the default processing and use Parsley purely from javascript.
it seems like what you really want this: http://parsleyjs.org/documentation.html#parsleyfield
check out parsley-error-container
the trigger should be $( '#myInput' ).parsley( 'validate' );
or not 100% sure on this but you should be able to call each one like this:
$( '#myInput' ).parsley('alwaysFalse');
and if they need inputs or data:
$( '#myInput' ).parsley('alwaysFalse','inputs','data');
Related
I have a beginner's question on Formvalidation.io. Maybe it's not even specific for that library but more related to Javascript in general.
I'd like to disable a validator after a certain field (let's say its name is postcode) has been validated and is valid. However, all my approaches result in either the validator not being disabled or being disabled if any field of my form is valid (not only the specific one).
I use the core.field.valid event and the library's documentation states:
The event parameter presents the field name.
I'm uncertain how that happens.
I tried:
document.addEventListener('DOMContentLoaded', function(e) {
const fv = FormValidation.formValidation(
document.getElementById('adminForm'),
{
fields: {
postcode: {
validators: {
notEmpty: {
message: 'Please enter a postcode.'
}
}
}
},
plugins: {
submitButton: new FormValidation.plugins.SubmitButton(),
defaultSubmit: new FormValidation.plugins.DefaultSubmit(),
trigger: new FormValidation.plugins.Trigger({
event: {
postcode: 'change',
}
})
}
}
);
fv.on('core.field.valid', function(e) {
if (e.field === 'postcode') {
fv.disableValidator('postcode');
}
});
});
But the if-condition is not true even when the field is validated and valid.
(tried to adapt it from the example given here)
I also tried what I found in the documentation on the on() method (as it states regarding function(field): "field is name of invalid field"):
const validFieldHandler = function(postcode) {
fv.disableValidator('postcode');
};
fv.on('core.field.valid', validFieldHandler);
Result is the same (validator is not disabled).
The following however (as probably to expect) disables the validator if any field of the form is valid.
fv.on('core.field.valid', function(e) {
fv.disableValidator('postcode');
});
Thank you for any advice you can offer! It's my first question here, so please let me know if you need additional information!
Best regards,
Sebastian
Found the solution myself:
fv.on('core.field.valid', function(field) {
if (field === 'postcode') {
fv.disableValidator('postcode');
}
});
I'm using jquery validation plugin to validate my form. The function below, displays errors under each field where the error is detected.
errorPlacement : function(error, element) {
error.insertAfter(element.parent());
}
});
How can I evaluate if this function has been used "error has been displayed on screen" or not?
What I'm trying to is to evaluate if form has been validated or not, so I can perform other logic such as disabling submit button or changing button text to "please wait for example".
I'm not sure how I can go about doing that.
Any help would be appreciated.
Thank you
Why don't you just set a boolean variable indicating that the method has been called:
hasError: false,
errorPlacement : function(error, element) {
error.insertAfter(element.parent());
this.hasError = true
}
Then you can check the hasError whenever you need to. Be sure to store hasError on an object in order not to pollute the global namespace.
You could use submitHandler, as it is a callback for handling the actual submit when the form is valid. So ,
$("#your-form").validate({
.....
submitHandler: function(){
//form is valid
//do some logic
$('#your_submit_btn_id').attr('disabled','disabled');
},
.....
});
You can always handle submit event using this code:
$("#myform").validate({
submitHandler: function(form) {
// some other code
// maybe disabling submit button // $('#submit').attr('disabled', true);
// then:
$(form).submit();
}
});
submitHandler will only get called once form gets validated & there is no error.
Documentation can be found here: http://jqueryvalidation.org/documentation/
You can take a look on this:
http://jqueryvalidation.org/validate/
http://www.kianworknotes.com/2013/06/error-handling-in-jquery-validation.html
DEMO
/*error and element is parameter*/
errorPlacement: function(error, element) {
error.appendTo( element.parent("td").next("td") );
}
$('#myform').on('submit', function(){
if($(this).valid()) //this returns true if the form is valid, and false if there is some validation error
{
//submit the form
}
else
{
//disable the submit button or change text as desired
return false; //to avoid form submission
}
});
Got a quick question about a form validation using jQuery. So I have huge-butt form, which is validated and submitted properly. The only problem I keep running into is that when I try to submit it, and the form is invalid, the window does not scroll to the invalid field. It tries to - the view sort of jumps about half an inch above the submit button and that's it - the invalid field is not actually shown on the page. In terms of the jQuery default settings on the validator, I have the following code:
$.extend($.validator, {
defaults: {
messages: {},
groups: {},
rules: {},
errorClass: "error",
validClass: "valid",
errorElement: "label",
focusInvalid: true,
errorContainer: $([]),
errorLabelContainer: $([]),
onsubmit: true,
ignore: ":hidden",
ignoreTitle: false,
}
When the validator runs, this is the focusInvalid() function definition:
focusInvalid: function() {
if ( this.settings.focusInvalid ) {
try {
$(this.findLastActive() || this.errorList.length && this.errorList[0].element || [])
.filter(":visible")
.focus()
// manually trigger focusin event; without it, focusin handler isn't called, findLastActive won't have anything to find
.trigger("focusin");
} catch(e) {
// ignore IE throwing errors when focusing hidden elements
}
}
},
Finally, on form validation:
if ( validator.form() ) {
if ( validator.pendingRequest ) {
validator.formSubmitted = true;
return false;
}
return handle();
} else {
validator.focusInvalid();
return false;
}
focus isn't the correct function for scrolling the page to a particular element. You need scrollTop, or a similar function. There are several questions about this, I like this answer which includes a simple example, and even includes the alternative solution with animation.
Thanks guys! It was fixed by having the script add custom classes to the invalid forms and focusing on them. We tried scrollTop, but that didn't work at all, so we went with a focus scenario. The invalidHandler function code is below for anyone who's interested:
// invalidHandler to set focus to invalid controls
invalidHandler: function(event, validator) {
var $invalidElement = $(validator.errorList[0].element);
if ($invalidElement.hasClass('chosen-select')) {
$invalidElement.trigger('chosen:activate');
} else if ($invalidElement.siblings('ul.token-input-list').length > 0) {
var $inputToken = $invalidElement.siblings('ul.token-input-list').find('input');
$inputToken.focus();
}
}
I am trying to clear all error messages as well error highlighting when user click on the clear form button, below are actual requirements
Validate form using Jquery validation
When user click on a field error message should be cleared (per field)
On clicking reset button, every error should be cleared
here is my code
$( document ).ready(function(){
var validator = $("#register_form").validate({
validator.resetForm();
focusCleanup: true,
rules: {
// custom rules
},
messages: {
// custom messages
}
});
For me, first 2 things are working, but when I am trying to clear complete form, I am not able to do this.this is how I am trying to clear it
function clearInputForm(){
alert("");
var validator1 = $( "#register_form" ).validate();
validator1.resetForm();
$("#register_form")[0].reset();
}
But nothing is happening , though with $("#register_form")[0].reset();, form fields are getting clear, but error messages are not getting cleared.
Quote OP:
1) Validate form using Jquery validation
You cannot put the validator.resetForm(); method inside of the .validate() method.
.validate() is a plugin method where the only thing that can go inside is a comma separated map of the allowed options, {option:value, option:value, etc.}, as per the .validate() method documentation.
resetForm() method documentation
$("#register_form").validate({
rules: {
firstname: {
required: true
},
lastname: {
required: true
},
cell: {
required: true
}
},
messages: {
// custom messages
}
});
.validate() method DEMO: http://jsfiddle.net/P46gL/
Quote OP:
2) When user click on a field error message should be cleared (per field)
This is thanks to the focusCleanup option. As you've already done, set it to true and when you click on the field with an error, the error clears.
$("#register_form").validate({
focusCleanup: true,
rules: {
....
focusCleanup DEMO: http://jsfiddle.net/P46gL/1/
Quote OP:
3) On clicking reset button, every error should be cleared
You would call the resetForm() method from within a click handler of the reset button. This will immediately remove all error messages from the entire form and reset the validation plugin to its initial state.
$('#clearform').on('click', function () {
$("#register_form").validate().resetForm(); // clear out the validation errors
});
Make sure the reset button is type="button" or type="reset" or it will trigger validation.
<input type="reset" id="clearform" value="reset form" />
Clear Errors DEMO: http://jsfiddle.net/P46gL/3/
Clearing out the field data
You can clear out the values of the fields by calling a JavaScript .reset() like this.
$('#clearform').on('click', function () {
var form = $("#register_form");
form.validate().resetForm(); // clear out the validation errors
form[0].reset(); // clear out the form data
});
Full Working DEMO: http://jsfiddle.net/P46gL/4/
$("#register_form")[0].reset();, form fields are getting clear, but error messages are not getting cleared.
to do this you can put one more line below it:
function clearInputForm(){
alert("");
var validator1 = $( "#register_form" ).validate();
validator1.resetForm();
$("#register_form")[0].reset();
$('.error').hide();
}
Although you should do this way:
$( document ).ready(function(){
var validator = $("#register_form").validate({
focusCleanup: true,
rules: {
// custom rules
},
messages: {
// custom messages
}
});
$('[type="reset"]').on('click', function(){
validator.resetForm();
});
});
You should put your validator.resetForm(); in the click event of reset button.
If nothing works then try this approach (specially for clearing data purpose):
1- Form html:
<input type='reset' class="button_grey resetForm" value='Reset'>
2- Jquery validate
// you can add error fields
var validator = $("#clearform").validate({
focusCleanup: true
});
3- Reset the form
$('[type="reset"]').on('click', function(){
$("#clearform").closest('form').find("input[type=text], textarea").val("");
$('input:checkbox').removeAttr('checked');
validator.resetForm();
return false;
});
All error messages will be cleared
$('.btn-reset').on('click', function () {
$( "label.error" ).remove();
});
Thank you in advance for looking at this. :-)
The form validation itself works on other items where the field is simply required - that is no problem.
I am trying to set a numeric range for validation from my autocomplete dynamically.
I am using the bassistance.de JQuery validation found here.
Upon the select, I am calling a function, but it needs to be added to .validate() code instead of its own function (I think), but now sure how to combine them.
The autocomplete is a generic function that is called by multiple inputs.
<script>
$().ready(function() {
// validate the form when it is submitted
$("#form4100").validate();
});
</script>
<script>
function Autocomplete(numberLocation,nameLocation,dscLocation,chargeLocation,amountLocation) {
select: function( event, ui ) {
$(numberLocation).val( ui.item.value );
$(nameLocation).html( ui.item.desc );
alert("Minimum Investment: "+ui.item.minimum);
setvalidation(amountLocation,ui.item.minimum);
return false;
}
}
function setvalidation(amountLocation,minimum){
alert("validation function launched");
amountLocation.validate({
rules: {
field: {
required: true,
range: [minimum, 5000000]
}
}
});
}
</script>
Thanks!
I found out (after reading the docs further on the validation plugin) that there is a .rules add method. So the .select can call this function:
function setvalidation(amountLocation,minimum){
amountLocation.rules("add",{
required: true,
range: [minimum, 5000000],
messages: {
range: "$ "+minimum + " Minimum"
}
});
}