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

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.

Related

Custom validation with bootstrap V5

So right now im basically using the default Bootstrap V5 form validator and I was wondering if there is a way to make a custom parameter that needs to be checked in order for the input to be valid. Right now I want the user to input their licenseplate, which must include letters and numbers. I more or less got the must include part, but bootstrap still says that the input is valid, even if its technically not, because it only checks if there is any input in the field. Would there be a way for me to change what bootstrap views as valid?
The default bootstrap validation function looks like this:
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function () {
'use strict'
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.querySelectorAll('.needs-validation')
// Loop over them and prevent submission
Array.prototype.slice.call(forms)
.forEach(function (form) {
form.addEventListener('submit', function (event) {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated')
}, false)
})
})()
After just spending the better part of the afternoon researching the same topic, there is very little information on custom JS validation with the OOB Bootstrap validation. I've concluded there are two viable options:
Using the pattern attribute on the element
Calling your own JS validation as part of the checkValidity() expression
Pattern Attribute
When creating an input, you can set a pattern attribute on the element.
From the MDN pattern article:
<p>
<label>Enter your phone number in the format (123) - 456 - 7890
(<input name="tel1" type="tel" pattern="[0-9]{3}" placeholder="###" aria-label="3-digit area code" size="2"/>) -
<input name="tel2" type="tel" pattern="[0-9]{3}" placeholder="###" aria-label="3-digit prefix" size="2"/> -
<input name="tel3" type="tel" pattern="[0-9]{4}" placeholder="####" aria-label="4-digit number" size="3"/>
</label>
</p>
Here we have 3 sections for a north American phone number with an implicit label encompassing all three components of the phone number, expecting 3-digits, 3-digits and 4-digits respectively, as defined by the pattern attribute set on each.
JS Validation
When invoking the checkValidity() method, inject custom JS validation to invalidate the form's submission.
const myValidation = someValidation()
if (!myValidation || !form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
When invoking someValidation(), be sure to add/remove the validation classes as-needed:
// valid input
const foo = document.getElementById("foo")
foo.classList.remove("is-invalid")
foo.classList.add("is-valid")
// invalid input
const bar = document.getElementById("bar")
bar.classList.add("is-invalid")
bar.classList.remove("is-valid")
However, I haven't quite figured out how to completely prevent the validation framework from showing the input as valid (checkmark on the right side of the input) even though the classes are set appropriately. I suspect it has something to do with the pattern attribute being empty, which simply means the field cannot be empty, and also needing to invoke the element's reportValidity() method: HTML Spec: reportValidity()
Conclusion
Looks like the pattern attribute and RegEx is the path forward when using this validation framework.
Hopefully someone else can improve this answer with a better path forward using the pure JS method.

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 Mobile Mail Form - capturing data from "select" field

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) {

How to apply validation for Dynamically added fields

Iam using javascript validation methods and rules for my form.And it is working fine.But I have an option that user can add many phonenumbers using clicking on a button Add More.But how to validate those fields through javascript.Bec we did'nt know how many fields user can add...I have tried with
jQuery.validator.addClassRules({
'phneClass' : {
required:true,
numeric : true
},
'name' : {
required : true
}
});
I need to give 2 diff messages for the both required fields.How can I achieve that.Thanks in advance.
You are using this validator: http://jqueryvalidation.org/?
Has your input fields the class 'phneClass'?
Maybe your have to call the addClassRules method after you added a new phonenumber field
Cheers
In that you can add html5 required attr to the generated input field inside the form that makes validation
check this link also
http://www.the-art-of-web.com/html/html5-form-validation/
http://www.wufoo.com/html5/attributes/09-required.html

jQuery validation & ignore field

I have a form with id myform and two fields (dates) with date class.
I would like to avoid jquery.validation (unobstrusive jquery validation on ASP .NET MVC3) for these two fields. I tried :
$('#myform').validate({
ignore: ".date"
});
However it doesn't work, I always have an error (Please enter a valid date.).
I need help please !
Thanks,
Ed
It works fine to me as described at the documentation http://jqueryvalidation.org/validate
$("#myform").validate({
ignore: ".ignore"
});
And, for multiple field use:
$("#myform").validate({
ignore: ".ignore, .another_class"
});
For anyone who is trying this alongside jquery.validate.unobtrusive, you may find it's ignoring all options passed into $("#myform").validate() and you'll have to set them on the object instead:
$('#myform').validate().settings.ignore = ".date";
$('#myform').valid();
The Unobtrusive plugin calls validate() when the document loads, which sets the options to defaults. A validator will then be created and cached, and any further calls to validate() will ignore new options and return the cached validator.
You need ignoreTitle, according to This Doc.

Categories

Resources