Individual Input Validation on Blur - javascript

I'm trying to use HTML5 to validate a number input. I am using jQuery to create the element. How can I have the browser display the error message onBlur without having to click the submit button?
jQuery(document.createElement('input')).attr({"type":"number","min":"0","max":"60","step":"1","value":"5"});

Set up a .blur() handler. See here.

jQuery(document.createElement('input')).attr({"type":"number","min":"0","max":"60","step":"1","value":"5"}).blur(function(){
var val = parseInt(jQuery(this).val(),10);
if(val < parseInt(jQuery(this).attr('min'), 10))
jQuery(this).val(parseInt(jQuery(this).attr('min'), 10)); // Set value to min
if(val > parseInt(jQuery(this).attr('max'), 10)){
jQuery(this).val(parseInt(jQuery(this).attr('min'), 10)); // Set value to max
});
Something along those lines

Actually, you can't invoke the native validation ui through an API. Due to the fact, that the the validation ui automatically also focuses the element, this would not be a good usability (user can't leave field invalid and decide to do something else on the page).
If you want to do this: you have to implement the validation yourslf using the validity property and the validationMessage property. The code could look like this:
$('input[type="number"]').blur(function(){
//if field is validation candidate and is invalid alert the validationmessage
if( $.prop( this, 'willValidate' ) && !$.prop( this, 'validity').valid){
alert( $.prop( this, 'validationMessage' );
}
});
Of course using an alert, is a little bit stupid, but makes the code clean. If you want to use webshims lib, there is a showError helper. I have put up a demo here
About the helper method $.webshims.validityAlert.showFor:
showFor requires a dom element jQuery object or selector as first argument.
the validationmessage as optional second
and the last is a boolean, which will show the message without focusing the field.

Related

Problems with executing code after a for-in-Loop

I have a form with multiple added dynamic rows, and i want to do a little validation of the input before i submit the form, e.g. check if all fields have input and such.
So i call this little function when i have an onclick-Event on my Submit-Button:
function validateAndSubmit() {
var form = document.getElementById("mainForm");
var formGroups = document.getElementsByClassName("form-group");
for (var x in formGroups) {
// Validation goes here
....
if (valid == false) {
return;
}
}
form.submit();
So in my logic, the code should iterate over each form-group (which basically represent the individual rows in the form) and check if they are valid. After the first invalid row, the function will return without any result. But if all formGroups are checked, the for-Loop will exit and the form.submit(); call will submit the form.
However, the final submit does not happen. Even if all form elements have valid input, the form does not submit. However, during some debugging i commented out the whole for-loop, and the form submits, but with no validation, of course.
So i am assuming that somehow the for-loop does not exit properly, and could need some help with that problem.
The whole project is written in plain Javascript, however, the library i am using to dynamically add and remove items to the form bases on jQuery.
For reference, you can find the project online here
you shouldn't use for-in at the first place. Just use the plain for form:
for(var i=0;i<formGroups.length;i++)
remember, for-in is for Objects / dictionaries. eg. {'key':'value'}
the first "x" you got in your loop is "length" - your formGroups[x] became formGroups[undefined] and throw an exception instantly.
You could also use a jQuery selector to get the elements. In your example,
$('.form-control').each(function() {
// Validation goes here
console.log($(this));
});

HTML5 validation: JavaScript weirdness with willValidate

OK this is a weird one. I'm sure I'm missing something obvious.
http://jsfiddle.net/wVp8j/
HTML:
<form>
<input type='text' required />
<button>check field validity</button>
</form>
JS:
var field = document.querySelector('input[type=text]');
document.querySelector('button').addEventListener('click', function() {
alert('Validates: '+field.willValidate);
alert('Value missing: '+field.validity.valueMissing);
}, false);
If the form is submitted with the field left blank, submission is suppressed, as you'd expect, but the first alert, checking the field's validity state, gives true. Why?
To contradict this further, the second alert confirms there's a problem with the field and also gives true, as expected.
What am I missing?
[Sidenote: MDN seems to think willValidate is a method, not a property.]
[EDIT]
As the commenter below points out, willValidate says whether the field is a candidate for validation, not, despite its misleading name, whether the field will validate.
Which presumably means the only means of telling whether a field will validate, should the form be submitted, via JS, is to iterate over its validity object and see if any flag is set to true.
[EDIT 2]
Turns out you can just check validity.valid on a field, even though the valid flag doesn't show up if you console.log the entire validity object. This would appear to be the way, therefore, to find out whether a field will hypothetically validate.
willValidate is a property that says whether or not an input can be validated, not if it is valid or not. The only time that willValidate is false is if the input element is disabled or the like.
See http://www.html5rocks.com/en/tutorials/forms/constraintvalidation/#toc-willValidate
Use field.validity.valid instead to check for validity.
http://jsfiddle.net/3xFua/
(function() {
var field = document.querySelector('input[type=text]');
document.querySelector('button').addEventListener('click', function() {
console.log('Validates: ', field.validity.valid);
console.log('Value missing: ', field.validity.valueMissing);
}, false);
})();
The documentation suggests using .checkValidity() which
Method Description
checkValidity() Returns true if the element's value has no validity problems; false otherwise. If the element is invalid, this method also causes an invalid event at the element.
while (as #soktinpk's answer correctly states) .willValidate simply flags it as available for validation, not passing validation.
Thus I recommend using this:
function() {
alert('Validates: '+field.checkValidation());
alert('Value missing: '+field.validity.valueMissing);
}
off-topic, alert is a terrible debugging tool. Consider using console.log or debugger;

jQuery Validate - how to use the errorMap or errorList

This may seem like such a novice question but here it goes. Inside my invalidHandler for the jQuery Validate plugin I have the following.
invalidHandler: function(form, validator) {
$firstitem = (validator.errorList[0].element);
alert($firstitem);
}
All I want to do is get the name of the first item in the errorMap or errorList. Here are some things I have tried:
alert($firstitem.attr('name')); also alert($firstitem.html());. Not sure how to access the name from here. I could just query the DOM, but the error elements may not have been updated so $("#form .error"); may not pick up the updated error set if any exists.
Any ideas ?
$firstitem is just a node here, not a jQuery object, so it should have its name as a property, $firstitem.name.
At the very least, you can console.log($firstitem) to see what it looks like.

jQuery validation plugin - partial validation depending on trigger

I am using the jQuery validation plugin and I would like to validate a floating point number and format it to a specified number of decimal places.
I am using
element.value = parseFloat(value).toFixed(param);
to format the floating point value if it is indeed a valid floating point value, I just only want to do this on blur, not on keyup as this yields odd results. I do however want to validate the input on keyup.
I guess what I am looking for is basically
if( validation was triggered by blur )
{
element.value = parseFloat(value).toFixed(param);
}
The jQuery validation plugin does not allow you to mix rules like that (I might be wrong, there may be an option to do that, but this problem is easy enough to solve without it anyway.)
First, for the keyup validation:
$('#float').keyup(function(){
if(!/[-+]?[0-9]*\.?[0-9]+/.test(this.value)){
// Do something about the error
}
});
You might want to rollback the edit or display an error message, whatever. Now, on blur
$('#float').blur(function(){
var input = this.value;
if(/[-+]?[0-9]*\.?[0-9]+/.test(input)){
this.value = parseFloat(input).toFixed(param);
}
});
There, simple.
NB: Regex from http://www.regular-expressions.info/floatingpoint.html

client-side text-box character limit validation using jQuery?

I have a textbox that must have a MIN number of characters as well as a MAX number of characters. What is the best way, using jQuery, to make sure that the input is within the range (while displaying status messages to the user) before allowing the user to submit the form?
Update: the code below works to some degree, however I am getting issues when deleting text. Since it is using 'keypress' to capture events in the textbox, the 'length' variable gets falsely incremented when hitting backspace for example. It seems like the issue is that the length of the text is retrieved before the fact i.e. a keypress will always result in a length of what was there before plus 1. What is the proper way around this?
Update: I think i solved the previous issue by using the keyup function instead of keypress
If this is the only client side validation in your app (always validate on the server too!) then it'd look something like this:
$("#your_textbox").keypress(function() {
var length = this.value.length;
if(length >= MIN && length <= MAX) {
$("#your_submit").removeAttr("disabled");
$("#your_validation_div").hide();
} else {
$("#your_submit").attr("disabled", "disabled");
$("#your_validation_div").show();
}
});
If you need a lot of validation in your application you might want to consider the validation plugin.
Setting the maxlength attribute:
<input type='text' maxlength="30" />

Categories

Resources