jQuery validation plugin - how to style 1 validation message differently to others - javascript

I have a form that is being validated with the jQuery validation plugin successfully.
Messages are displayed in the correct position and in the correct situations.
So far, so good.
I have 1 field that is being validated correctly, but I need to position that 1 validation message differently to the others. With 2 inputs next to each other, I want the validation to appear under them both (ie under the block that wraps them both) rather than to the right per individual inputs.
The validation on these 2 inputs are dependent on each other, ie at least one must have input. The validation rule works, it's just the positioning I'm struggling with.
I'm using the following validation syntax:
$('#formId').validate({
rules: {
},
messages : {
}
}
In my HTML I have created a label specifically for the (radio) field I am trying to customise:
<label for="radioName" id="radioNameId-invalid" class="error"">Some error message</label>
I tried adding content to the 'showErrors' function of validate, which works, but seemingly then doesn't show any of the other validation messages in my page.
showErrors: function(errors) {
var collectionMethodError = errors['collectionMethod'];
if(collectionMethodError) {
$('#radioNameId-invalid').text(errorString);
$('#radioNameId-invalid').css("display","block");
}
}
I want to enable this error AND then allow validator to continue to do its default behaviour for other fields.
If I remove the showErrors function, the other validation messages are displayed but not my custom one.
How can I get both behaviours?

I ended up using the errorPlacement function instead of the showErrors function:
errorPlacement: function(error, element){
$(error).insertAfter(element);
// special case for display
if($(element).attr("name")=="radioName") {
$(error).insertAfter("#anElement"));
$("label[for=radioName].error").attr("id","invalid-radio-message");
}
}
So in short I'm adding an ID to a label that validation plugin adds, then styling to that ID in my css.
That seems to do what I was trying to do. Now to workout the re-hiding of the message!

Related

Warn on non-ASCII Characters in Django Form

I'm trying to add some client-side Ajax validation of my Django form. I want to warn users, as they are typing in a field, if any of the characters they just inputted are not ascii.
I originally put the basic python to check for ascii characters in my form's clean method. I don't want to do that, though, as I don't want to produce an error but rather just give a warning message and let the user continue with the rest of the form.
try:
field_value.decode('ascii')
except UnicodeEncodeError:
#raise forms.ValidationError("Non-ASCII characters may cause issues in registering your data. Consider removing these characters. You may still submit at your own risk.")
# Just want to show a warning so the user can still submit the form if they wish
I want to show a small warning under the field as the user is typing. I've tried using django-dajax, but am not sure. How can I do this?
EDIT:
To clarify, I want to show the warning before the user submits the form. So, as they are filling out the form...
Use
> <input type="text" pattern="^[\x20-\x7F]+$" id ....>
in html
Use JavaScript to validate that form field.
Example (using jQuery):
<form>
<input name="whatever" id="fieldId">
...
</form>
<script type="text/javascript">
/* Define a function to check the form field value */
function containsAllAscii(str) {
return /^[\000-\177]*$/.test(str); // returns true if all are ASCII characters. false otherwise.
}
/* Now a little jQuery */
$('#fieldId').on('change', function() {
str = $(this).val();
is_valid = containsAllAscii(str);
if (!is_valid) {
window.alert("There are Non-ASCII characters in the input field");
}
});
</script>
The above code will check the given field's value whenever it changes (i.e. loses focus). You can use .on('keyup', ... instead of .on('change', ... which will check the field's value as the user is typing.
Finally, the error message that is shown is just a browser alert. Which is crappy. You can display a beautiful error message, you just need to learn a little more of jQuery. But I hope I've given you a good starting point.
Credits:
The code for containsAllAscii function is taken from this answer by Juan Mendes.
In your django form, create a custom field and take advantage of the media class.
from django import forms
class MyWidget(forms.TextInput):
class Media:
css = {
'all': ('pretty.css',)
}
js = ('animations.js', 'actions.js')
and set the js to the javascript file you will use for validation. something along the lines of the the other answer
https://docs.djangoproject.com/en/1.9/topics/forms/media/

Unable to change minLength dynamically

I have a dropdown which has countries and in the same form on 2nd line I have ZipCode texbox. I want to limit the minLenght of the zipcode field dynamically. For example If US is slected zipcode should not be less than 5 and for other countries some other minLength Limit. My form uses a parsley validator
I wrote below function onChange event of my country dropdown
function setZipLimit() {
alert("in Zip limit" + document.getElementById("billingCountry").value);
if (document.getElementById("billingCountry").value == "US") {
alert("I am in US");
$('#billingForm').parsley('destroy');
$('#billingPostalCode').data('minlength', 3);
$('#billingForm').parsley();
} else {
$('#billingForm').parsley('destroy');
$('#billingPostalCode').data('minlength', 10);
$('#billingForm').parsley();
}
}
But this doesnt seem to be helping. Can you please help me?
You cant just edit the Attribute, because parsley.js initially Reads the form and gets its Values. Changing them Afterwards shouldnt have any Effect.
However you can use the Parsley.js API for Javascript functions to Edit the constraints. You already used them to destroy and Build Parsley. Parsley got the following Function:
$( '#field' ).parsley( 'updateConstraint', { minlength: 6 } );
There are also some with addConstraint and removeConstraint in the Documentation:
http://parsleyjs.org/documentation.html
If your Form gets more complex and you have several of those dynamic cases, i recommend to only Destroy and Rebuild specific Parts of your Form. The Reason is (from an issue I had recently):
If you Destroy Parsley, change some Fields, build Parsley and then Destroy it again because another if Statement takes place, your previous Changes get thrown away, because Build only reads the js inbetween the Destroy and Build and reads the Form.

Conditional Required Fields validation is not working

I've got a new enigma for you to solve, because I can't manage to get this working.
Imagine yourself working for an online marketing company with a proprietary platform to host and manage campaigns. And then imagine only being able to validate required fields that 'just are there'. And at last; imagine a client that needs form fields to be required after a certain radio button is checked. Right? Right! Well.... no... not right.
Here is the thing. That same radio button triggers a jQuery script that eases in the 5 div's with form fields that are hidden display: block. I have the jQuery.validation.js plugin at the ready.
I insert this piece of code to the form fields that are required if it meets the condition that the depending field is checked:
class="textInput1 validate[condRequired[radiobuttonX]]"
textInput1 is a CSS class that styles an input field.
As a submitbutton I use an image which uses this code to submit: input type="image"
onclick="document.forms['formName'].submit();"
I have got:
$(document).ready(function() {
in place and in my head I have the link to the validation script:
<script src="../path/to/jquery.validationEngine.js"></script>
I use the: Inline Form Validation Engine 2.6.2, jQuery plugin
How do I make form field Y required when radiobuttonX is ticked? I definitely need syntax as well, because I'm a dumbs ;-)
If you can switch fromjQuery Validation Engine to jQuery-Validate, this would be the solution:
$("#form").validate({
rules: {
fieldY: {
required: {
depends: function() {
return $("#radioButtonX").is(":checked");
}
}
}
}
});

HTML5 Form Validation

I have two major problem regarding HTML5 form validation.
1- I use this code to change the validation message of inputs
$$('INPUT').each(function(input)
{
input.oninvalid = function(event)
{
event.target.setCustomValidity('');
if (!event.target.validity.valid) event.target.setCustomValidity('Please Fill');
};
}
There's a big problem with this method. As the form is submitted if the input is invalid, an error message is attached to it. So it wouldn't validate on new input. Even after correction and submitting again it won't let the form get submitted because the message is still attached. so event.target.setCustomValidity('') will remove the message and form needs another submit. two submit after correction.
I couldn't find a way to correct this behavior.
2-How can I hide or disable these tooltips totally but still use form validation. Sometimes I want to use css invalid and valid pseudo classes, but these tips are still displayed.
I find formnovalidate on submit button and then I can check validity.valid of each inputs manually before submitting. any better idea?
In terms of question 1:
I had an input
<input name="VoucherCode" id="VoucherCode" type="text" pattern="(1[0-9]{9})|(2[0-9]{9})" value="">
And improved the default message
$("#VoucherCode").on("invalid", function (event) {
event.target.setCustomValidity('The format of Voucher Code is not correct.')
});
But this had the same problem you encountered: if the user gets the first attempt wrong, a correct response still show the invalid pattern message.
I fixed this based on #Pointy's suggestion:
$("#VoucherCode").on("invalid", function (event) {
event.target.setCustomValidity('The format of Voucher Code is not correct.')
}).bind('blur', function (event) {
event.target.setCustomValidity('');
});
(a bit late) but the solution could be around there!
What happen:
Since you customize the error message event.target.setCustomValidity("...") the property in the element.validity.customError is true ; the reportValidity with always return false and the submit wouldn't be valid
What I did?
When the User change the input (event.on Change) - I set up back the default error message event.target.setCustomValidity(''); this will tells the Browser to keep working without a custom error

MVC3 unobtrusive validation: how to remove/re-attach validation from a group of elements?

Here's the use case:
I have this long form with group of field that only becomes visible if the user makes a certain selection in one of the visible inputs. Reading Brad Wilson's post on the subject I thought jQuery.validator.unobtrusive.parse('.extra-data') where .extra-data is a class of a hidden div. No luck as the data was already there when the first parse was done.
So at the end I came up with this to remove the rules:
$('.data-panel').find('input[type="text"], textarea, select').each(function (i, item) {
var currentRules = $(item).rules('remove'); // Saving removed rules to a sorta dictionary
if (!$.isEmptyObject(currentRules)) {
removedRules[$(item).attr("name")] = currentRules;
}
});
and this to re-attach them:
$('.data-panel').find('input[type="text"], textarea, select').each(function (i, item) {
if (!$.isEmptyObject(removedRules[$(item).attr('name')])) {
$(item).rules('add', removedRules[$(item).attr('name')]);
}
});
Problem is, it feels kinda hacky as I'm literally going through each field removing and re-attaching those validation rules. My question is: isn't there a more straightforward way? Performance is also an issue, in one of those huge forms you can feel the delay between the click and the validation run.
Do not remove and re-attach rules. Just disable or enable inputs. Disabled fields do not participate in validation, neither do they get submitted to server.
//disable inputs. No validation will occur on these
$('.data-panel').find('input[type="text"], textarea, select').attr('disabled', 'disabled');
//enable inputs. Validation is re-enabled
$('.data-panel').find('input[type="text"], textarea, select').removeAttr('disabled');

Categories

Resources