JQuery Mobile Mail Form - capturing data from "select" field - javascript

I used the following solution for a mailer form for my JQuery Mobile site:
http://eisabainyo.net/weblog/2011/06/29/creating-a-contact-form-in-jquery-mobile-and-php/
Everything works fine, except the "required" function does not properly parse values for HTML "select" elements:
$('.required', $contactform).each(function (i) {
if ($(this).val() === '') {
error++;
}
}); // each
In other words, whenever I add the class "required" to a "select" form element, the form will not submit because it always triggers the error "Please fill in all the mandatory fields. Mandatory fields are marked with an asterisk" regardless of what item is selected.
Source article is from June 2011, so my guess is that this function doesn't work with my version of JQuery (1.8.3) or JQM (1.3.2).
I'm not a Javascript expert, and this article unfortunately provides little documentation as to how exactly this function works. Any suggestions?

Use this instead of the line that you have:
$('.required', $contactform).not('span').each(function (i) {

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/

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

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!

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");
}
}
}
}
});

jQuery Tools Validator: not required, but test if not empty

I'm using the Validator from jQuery Tools to validate my form (why jquery tools? because they are lightweight and use semantic HTML5 Tags, input-types and params for validation) but I have one problem:
I want to let jQuery Tools Validator test/validate a input-field only if it is not empty — but the field is not required.
On fields that have to be tested/validated, I can use required="required" and it validates … now I have a text-input-field where the user can input a URL, this field is not required BUT if the user adds some data into that field, the field should validate with pattern="https?://.+" to get sure the user is entering a valid url... if I add the pattern-parameter and no required-parameter, jQuery Tools Validator does test/validate nonetheless and I'm not able to submit the form until I entered a valid URL — even if I do not want to enter a URL at all!
You could try modifying your regex to allow the empty string, such as
pattern="^(?:|https?://.+)$"
Is there any reason you're tied to jquery tools validator? I've had great success with : http://bassistance.de/jquery-plugins/jquery-plugin-validation/
So for example I'd add a custom jQuery validator field:
jQuery.validator.addMethod("unittype", function(value, element) {
return jQuery('#fuel option:selected').val() in unitOptions && value in unitOptions[jQuery('#fuel option:selected').val()];
});
jQuery('#fuel').rules("add", {
fueltype:true,
messages:{
fueltype:"Please select a fuel type"
}
});
That was just an example from my code, just substitute the regex into the method.
If you specify your form field as
<input type='url'/>
then jQuery Tools Validator will require a valid url--you shouldn't need to roll your own url regex.
And if you don't mark that field required, then the validator should only check the field when it's non-empty; which, if I understood correctly, is the behavior you (OP) want.

Categories

Resources