parsley.js - disable the maxlength validation - javascript

I am trying to dynamically disable the parsley.js max length on several of my input fields when the user makes a selection on a select list on the form.
I have read this thread, but when I put the code into my field, the parsley is not triggered, instead the form submits, and I do not understand why.
I have read the parsley.js docs, but I am unable to see why the parsley.js validation is ignored when i add the following line of code:
$('#id_employment_record_position_title').attr('data-parsley-maxlength', '0');
or
$('#id_employment_record_position_title').attr('data-parsley-maxlength', '150');
This is my code to dynamically turm the parsley validation on and off when the user changes the select list on the form:
function toggleFormDetails() {
if ( $('#id_employment_record_display_type').val() == '8888' || $('#id_employment_record_display_type').val() == '9999' ) {
//disable the input field.
$('#id_employment_record_position_title').prop('disabled', true);
....
//destroy parsley on the form.
//$('#employment_history_details_form').parsley().destroy();
//disable the parsley maxlength, when the input field is disabled.
$('#id_employment_record_position_title').attr('data-parsley-maxlength', '0');
//reinitialise parsley on the form.
//$('#employment_history_details_form').parsley();
} else {
//enable the input field.
$('#id_employment_record_position_title').prop('disabled', false);
....
//destroy parsley on the form.
//$('#employment_history_details_form').parsley().destroy();
//change the parsley cs error values for all the required form inputs.
$('#id_employment_record_position_title').attr('data-parsley-maxlength', '150');
//reinitialise parsley on the form.
//$('#employment_history_details_form').parsley();
}
}
Why do I have have to add the destroy & create parsley code on the form (I have commented them out above)?
Would it be better to write a custom validation for this? If so, how would I do that, b/c my js code skills are not yet good enough?

Parsley is a Javascript library and works something like this:
When you render your html form, you specify the needed validations through data attributes.
You indicate that the form will be validated by Parsley either with the form attribute data-parsley-validate or via javascript through $("#form").parsley().
When parsley is binded to your form (the second step), an object of the type ParsleyForm will be created containing the constraints for each field.
After the object is created, the html attributes are no longer needed. So, if you change any attribute it will have no impact on the validation since Parsley will verify the constraints of the javascript object. This is why you need to destroy & bind parsley (in order to recreate the parsley instance with the new constraints).
In order to solve your issue, you could do something like this:
<form id="myForm" class="form-horizontal" method="post">
<input type="text" name="id_employment_record_display_type"
id="id_employment_record_display_type"
placeholder="Set 8888 to discard maxlength validation" />
<input type="text" name="sample" id="id_employment_record_position_title"
data-parsley-maxlength="150" />
<button type="submit">Submit</button>
</form>
<script>
$(document).ready(function() {
$("#myForm").parsley();
$("#id_employment_record_display_type").on('change', function() {
$("#myForm").parsley().destroy();
if ( $(this).val() == '8888' || $(this).val() == '9999' ) {
$('#id_employment_record_position_title').removeAttr('data-parsley-maxlength');
$('#id_employment_record_position_title').prop('disabled', true);
} else {
$('#id_employment_record_position_title').attr('data-parsley-maxlength', '150');
$('#id_employment_record_position_title').prop('disabled', false);
}
$("#myForm").parsley();
});
$("#myForm").submit(function() {
$(this).parsley().validate();
// when there are no client side errors when the form is submitted
if ($(this).parsley().isValid()) {
console.log('no client side errors!');
} else {
console.log('form is not valid');
}
event.preventDefault();
});
});
</script>
You can also check this working jsfiddle

Related

Parlsey prevent keydown validation after initial validation call

I am validating a form using Parlsey like so:
$(document).on("click", ".submit-form-btn", function(e) {
$(".form-class").off().submit(function(e) {
e.preventDefault();
$(this).parsley().validate();
if ($(this).parsley().isValid()) {
//Do something
}
});
});
After the initial validation, validation checks appear to be calling on every "keydown" press. How can I only validate again when my ".submit-form-btn" is clicked on again? I only want validation checks on click.
You can achieve this by adding the data-parsley-trigger-after-failure attribute with a value of submit. This will then ensure only submits will trigger further validation. You can either add it to individual fields (causing some fields to continue to validate on input while others will only validate on submit), or to the entire form (to specify submit-only validation everywhere):
<form id="form" data-parsley-trigger-after-failure="submit">
or:
<input type="text" required data-parsley-trigger-after-failure="submit">
Here's a Codepen example.

re-enable an input after it was disabled through javascript because it was empty

I am using jQuery Validator to validate a form and I wanted to disable the fields that were blank when the user clicks submit so that the server does not receive any data from the inputs that were left blank. To disable them, I used the following Javascript:
$(function() {
$("#form1").submit(function() {
$(this).find(":input").filter(function(){ return !this.value; }).attr("disabled", "disabled");
return true; // ensure form still submits
});
});
Here is my problem: This code works great assuming the form was validated on the first submission. However, if the user hits submit but it was not validated, all of the alerts for various required fields and such pop-up, but all of the inputs are disabled. How can I fix this? I need to know how to re-enable them if the form is not validated and properly submitted.
It doesn't make sense to disable the field to submit. Rather—you should first do a front-end only validation that prevents submitting if there are empty fields (and those fields are required to not be empty).
You can set up a variable (or a function) to run through your validation and only submit if it returns true. This is a condensed example of just one input.
var validate = ($('input').val() == '') ? false : true;
if(validate){
// submit your form
} else {
// throw your errors
}
Then it would be good to clear your errors at the beginning of your validation.

Bootstrap form input: prevent submit, but allow for input checking

I've got the following problem:
I use bootstrap form to take input from users, and I use jQuery preventDefault() to disable the submit button from sending the form (I use AJAX instead). However, that function also prevents input checking that is done by bootstrap. For example, if someone enters an e-mail without '#' into
<input type="email" class="form-control">
bootstrap would, upon clicking submit, check that input and return a popup with an error.
My question is: how to prevent the request being sent while keeping the bootstrap form checking mechanism intact?
What I have tried: using preventDefault() and writing my own checking script, however this seems like reinventing the wheel and having extra code when it's not needed.
Thank you!
I believe you are talking about the native HTML5 form validation and not validation by bootstrap its self, I have never come across bootstrap validation before. (i may be wrong though).
Most new browsers will validate <input type='email'/> as an email address and <input type='text' required='required'/> as required on form submission.
If for example you are using e.preventDefault(); on the click event on the submit button the form will never attempt to submit and hence the native validation will never happen.
If you want to keep the validation you need to use e.preventDefault(); on the submit event of the form not the click event on the button.
The html...
<form action='' method='post'>
<input type='email' name='email' required='required' placeholder='email'/>
<button type='submit'>Submit</button>
</form>
The jQuery...
//this will stop the click on the button and will not trigger validation as the submit event will never be triggered
$("button").on('click',function(e){
e.preventDefault();
//ajax code here
});
//this will stop the submit of the form but allow the native HTML5 validation (which is what i believe you are after)
$("form").on('submit',function(e){
e.preventDefault();
//ajax code here
});
Anyway hope this helps. If I have misunderstood in any way let me know and ill try to assist further.
I had the same issue, I came to use "stopPropagation" as the way to stop the form submission. But after a little reading on jQuery 3, I realized that "preventDefault" was enough to what I wanted.
This caused the form validation to happen and the submit event didn't proceed.
(This example is of an attempt i had on my own).
$('form').on("submit",function( event ) {
if ( $('#id_inputBox_username').val().length == 0 &&
$('#id_inputBox_password').val().length == 0 ) {
event.preventDefault();
$('#id_inputBox_username').tooltip('show');
$('#id_inputBox_password').tooltip('show');
} else if ( $('#id_inputBox_username').val().length == 0 ) {
event.stopPropagation();
$('#id_inputBox_username').tooltip('show');
} else if ( $('#id_inputBox_password').val().length == 0 ) {
event.stopPropagation();
$('#id_inputBox_password').tooltip('show');
}
});
I had the same problem and I find this solution:
$('#formulario').on('submit', function (e) {
if (e.isDefaultPrevented()) {
// handle the invalid form...
} else {
// everything looks good!
e.preventDefault(); //prevent submit
$(".imprimir").show();
$(".informacao").fadeOut();
carregardados();
}
})

Parsley.js validation

As an exercise I have added some parsley validation to this form here
http://matthewpiatetsky.com/cs401/login.html
I am now trying to add a similar validation to the form here
http://matthewpiatetsky.com/cs401/writereviews.html
(I have some mouseout validation on the text area)
I am running into two issues:
How can I get the form to validate before the form submits to its action? Can I run validation first, and if validation succeeds, then submit the form.
How can I add data-required="true" to the jquery raty stars to force the user to fill those in?
Thanks!
For validation before submit you can do something like:
var form = document.getElementById(“yourFormID”);
form.addEventListener("submit", function(event) {
// do your additional validation here
if (something wrong)
event.preventDefault();
}, false);

Jquery validator valid status with ajax submit

I am trying to post a form using ajax after a form has been validated. However the .valid seems to be wrong.
Multiple action type is desired based on button.
This example is also not showing the errors messages correctly upon submit
$('#submit').click( function(){
alert(validator.valid());
});
$('#submit2').click( function(){
alert(validator.valid());
//do something else
});
status become true if i enter a required field (e.g name)
this is the fiddle
try this fiddle
http://jsfiddle.net/r2HUu/4/
It's working. I just checked form' validation by $("#myForm").valid()
Quote OP:
"I am trying to post a form using ajax after a form has been validated"
As per documentation, your ajax goes inside the submitHandler callback function.
submitHandler (default: native form submit) Type: Function()Callback
for handling the actual submit when the form is valid. Gets the form
as the only argument. Replaces the default submit. The right place to
submit a form via Ajax after it validated.
Using this callback, the click is captured automatically and the function is only fired on a valid form.
$(function () {
var validator = $("#myForm").validate({
// rules and options,
submitHandler: function(form) {
// your ajax goes here
alert("valid form");
return false;
}
});
});
DEMO: http://jsfiddle.net/fXDwd/
Quote OP:
"However the .valid seems to be wrong."
EDIT
As per OP's comments and updated jsFiddle:
If you want to have multiple submit buttons do different things on one form, construct click handlers for each button which you've already done. Now you must move those buttons to outside of the <form></form> container. Otherwise, the plugin will treat them both as normal submit buttons and interfere with your click handlers.
The other problem is your implementation of .valid(). Attach it to the form element, $("#myForm"), not the validator initialization object.
HTML:
<form id="myForm" action="">
...
</form>
<input type="button" id="submit" value="Submit form" />
<input type="button" id="submit2" value="Submit form2" />
jQuery:
$(function () {
var validator = $("#myForm").validate({
// rules and options
});
$('#submit').click(function () {
alert($("#myForm").valid());
//do something
});
$('#submit2').click(function () {
alert($("#myForm").valid());
//do something else
});
});
DEMO: http://jsfiddle.net/vfrGU/

Categories