Custom validation with bootstrap V5 - javascript

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.

Related

Display tooltip/message while input is invalid HTML/JS/CSS/Angularjs

I have an HTML input field where certain characters shouldn't be allowed. The functional part is solved, but I would like to display a tooltip/message next to the input field while it contains illegal characters.
I have a boolean which keeps track of this, but I've been unable to make a satisfactory tooltip/message.
I've tried tweaking uib-tooltip, but It requires the user to hover over the input area. I've tried making a span/div/label that's hidden/displayed based on the boolean, but my CSS skills aren't strong enough.
The app uses Angularjs and Bootstrap 3.
The input field is not part of a form.
where you catch that boolean just say to display the div next to input like
myDiv.visible = true;
Without knowing your exact Javascript, I can't really answer it directly.
I would do something like
function invalid() {
if (invalid = true) {
document.getElementById("alert").style.visibility = 'visible'
}
}
make sure the error message is set to hidden,
then have the checker function run on focus..
<input type="text" onfocus="invalid()">
https://jsfiddle.net/we67geke/1/
This comment by user Lex solved the problem.
You can manually set the visibility of the uib-tooltip using the
tooltip-is-open attribute. Simply use the same boolean you are using
to keep track of the invalid characters.
As you mentioned
The app uses Angularjs and Bootstrap 3.
I suggest that you should use Boostrap tooltip. Use $('#element').tooltip('show') and $('#element').tooltip('hide') with your flag to handle status of Tooltip.
I don't know how your codes work, my idea seems like:
HTML:
<input type=text (keypress)="eventHandler()"> // angular >= 2
<input type=text ng-keypress="eventHandler()"> // angular 1
Angular code:
eventHandler() {
if (isIllegal) {
$('#element').tooltip('show');
} else {
$('#element').tooltip('hide');
}
}
Something like that.
Bootstrap Tooltip: https://getbootstrap.com/docs/3.3/javascript/#tooltips

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/

How do I get KendoUI Validator to ignore hidden form elements?

I am attempting to use KendoUI Validator with an ASP.NET WebForms project.
I have a simple page, that has a number of inputs, and of course ASP.NET adds some hidden form elements as well.
I have the following questions:
Why does the KendoUI Validator not ignore hidden form fields, and how to I get it to?
Why does KendoUI apply the rules to every input field, and how to do get it to ignore some fields. I want a declarative way to do this, not by adding all sorts of exceptions in my validation rule, as per the example in the KendoUI Validator API page.
Shouldn't it be that if no rule is set as an attribute in the input element (eg; required) then no validation is applied?
Behavior I am getting:
With no validation specific attributes on the input element at all, the validation rules still get applied when I call .validate()
Hidden form elements are validated.
I am using the following kendo:
http://cdn.kendostatic.com/2013.2.716/js/jquery.min.js
http://cdn.kendostatic.com/2013.2.716/js/kendo.all.min.js
http://cdn.kendostatic.com/2013.2.716/styles/kendo.common.min.css
http://cdn.kendostatic.com/2013.2.716/styles/kendo.default.min.css
I have put together a fiddle that demonstrates this:
http://jsfiddle.net/codeowl/B5ML4/3/
And here is the code, for those that don't have access to fiddle:
I have the following markup:
<form action="/" id="testForm">
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="text" id="testInput" value="">
<a id="testValidate" href="javascript:;">Validate</a>
</form>
and the following script:
var validatable = $("#testForm").kendoValidator({
rules: {
testRule1: function (input) {
// Only "Tom" will be a valid value for the FirstName input
return input.is("[name=firstname]") && input.val() === "Tom";
},
testRule2: function (input) {
return $.trim(input.val()) !== "";
}
},
messages: {
testRule1: "Your name must be Test",
testRule2: "Your name must be Foo"
}
}).data("kendoValidator");
$("#testValidate").click(function () {
if (validatable.validate()) {
alert('passed');
}
});
and when I press the validate link it shows validation messages for the hidden fields.
For anyone interested, I did eventually get a response to this question. I had to post it on the KendoUI Premium Forums to get someone to respond.
Here is the response:
How do I get KendoUI Validator to ignore hidden form elements?
Indeed, the hidden input elements are passed through the validation
rules logic by default due to the fact that there are multiple widgets
which has a hidden input as part of there markup. However, as the
built-in rules relays on the presence of certain attributes, if there
are missing no validation will happen on the hidden inputs. Therefore,
your own custom rules should handle this scenario and skip the
appropriate elements. For example:
testRule2: function (input) {
if (!input.is(":hidden")) {
return $.trim(input.val()) !== "";
}
return true;
}
I'm writing this for new comers.
Simply make hidden inputs disabled
$('#hidden_input').prop('disabled', true) // won't check in kendo or standard jquery validation
$('#hidden_input').prop('disabled', false) // will check in kendo or standard jquery validation
validator._inputSelector=
":input:not(:button,[type=submit],[type=reset],[disabled],[readonly],[type=hidden],:hidden)
[data-validate!=false]
This will not validate hidden controls. Kendo 2018 version

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.

Is there anyway to disable the client-side validation for dojo date text box?

In my example below I'm using a dijit.form.DateTextBox:
<input type="text" name="startDate" dojoType="dijit.form.DateTextBox" constraints="{datePattern:'MM/dd/yyyy'}" value='<c:out value="${sessionScope.adminMessageForm.startDate}"/>' />
So for example, if the user starts to enter "asdf" into the date the field turns yellow and a popup error message appears saying The value entered is not valid.. Even if I remove the constraints="{datePattern:'MM/dd/yyyy'}" it still validates.
Without going into details as to why, I would like to be able keep the dojoType and still prevent validation in particular circumstances.
Try overriding the validate method in your markup.
This will work (just tested):
<input type="text" name="startDate" dojoType="dijit.form.DateTextBox"
constraints="{datePattern:'MM/dd/yyyy'}"
value='<c:out value="${sessionScope.adminMessageForm.startDate}"/>'
validate='return true;'
/>
My only suggestion is to programmatically remove the dojoType on the server-side or client-side. It is not possible to keep the dojoType and not have it validate. Unless you create your own type that has you logic in it.
I had a similar problem, where the ValidationTextBox met all my needs but it was necessary to disable the validation routines until after the user had first pressed Submit.
My solution was to clone this into a ValidationConditionalTextBox with a couple new methods:
enableValidator:function() {
this.validatorOn = true;
},
disableValidator: function() {
this.validatorOn = false;
},
Then -- in the validator:function() I added a single check:
if (this.validatorOn)
{ ... }
Fairly straightforward, my default value for validatorOn is false (this appears right at the top of the javascript). When my form submits, simply call enableValidator(). You can view the full JavaScript here:
http://lilawnsprinklers.com/js/dijit/form/ValidationTextBox.js

Categories

Resources