How to display HTML5 validation if inputElement.validity.valid == false? - javascript

So I have a form, but I don't need to be submitting the information to the server just yet... What I need, is to just run the fields through the HTML5 built-in validation conditions (such as email, etc.), and if true, just execute a specific function...
So far, I've come up with this...
function checkform()
{
var /* all the elements in the form here */
if (inputElement.validity.valid == 'false')
{
/* Submit the form,
this will cause a validation error,
and HTML5 will save the day... */
} else
{
navigateNextStep();
}
}
That's the logic I've come up with so far, and its a little backhanded because I'm submitting KNOWING that there's an invalid value, hence triggering the validation prompts...
My only problem with the above logic, is that I have about, 7-8 input elements, and I find the option of doing the following rather, 'dirty':
var inputs = document.getElementsByTagName("INPUT");
if (!inputs[0].validity.valid && !inputs[1].validity.valid && ...)
Ideas?

You can just call formEl.checkValidity()... This will return a boolean indicating whether or not the whole form is valid, and throw appropriate invalid events otherwise.
The spec
A brief JSFiddle to play with
I'm not sure how you're expecting submitting the form to trigger the browser's validation UI, though. Calling formEl.submit() seems to result in a submission regardless of the validation state. This is noted at the bottom of The H5F project page, which says:
Safari 5, Chrome 4-6 and Opera 9.6+ all block form submission until all form control validation
constraints are met.
Opera 9.6+ upon form submission will focus to the first invalid field
and bring up a UI block indicating
that it is invalid.
Safari 5.0.1, and Chrome 7 have removed form submission blocking if a
form is invalid, most likely due to
legacy forms now not submitting on
older sites.

Ok, so this is awkward... Thanks to Domenic, and good ol' Google, I came across an alternative solution...
I ran a for loop, checking if each of the input elements were valid or not through the imputElement.validity.valid method, which returned a boolean value...
For every element that was valid, I incremented a variable by 1, and included a conditional statement in the loop to check if the variable had been incremented enough to execute the navigation function...
If there was an invalid field, the if statement would never execute, and (here's the fun part) the browser would validate the fields anyways, pop up saying which fields were broken and needed user correction... :-)
The For Loop...
for (i=0;i<8;i++)
{
if (inputs[i].validity.valid)
hg++;
}
if (hg==8)
skimregform();

You can programmatically trigger the checking of each field in your form, even if you set event.preventDefault() function.
document.forms["form_id_name"].reportValidity();

Related

Is there any way to get value of an auto-filled password box in JavaScript?

var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
inputs[i].onfocus = foo;
}
function foo(){
alert(this.value);
}
When the input values are manually entered:
Above code works and alerts the correct values regardless of the type of an input field.
When the input values auto-filled by browser:
Code works and alerts the correct values when the input field is of type text. In case of a password field, it alerts empty string!
Is this behaviour because of the browser's security policies? Or there's any workaround possible? I tried it in Chrome browser.
$(document).ready(function() {
$("input")
.blur(password)
.trigger('blur');
});
function password() {
alert($(this).val())
}
DEMO
This is an interesting question because I believe that you are referring to the side-effect of a security feature in Chrome.
Chrome (and probably other browsers) may not actually populate the DOM with the auto-filled password because a malicious programmer could write a JavaScript that attempts to steal auto-filled passwords from unsuspecting victims once a page loads.
You will most likely require that the user clicks a submit button before you can gain access to that information.
You might be able to force the form to submit and check the value right before the submit actually occurs. If that works, then you can just cancel the submission by returning false in "onsubmit" and you now have the password.

Debug jQuery form validation

I have a form that submits to a url using the action attribute <form action='/example/url'>. It uses the jQuery validation plugin.
jQuery("form#page-0").validate({
ignore: ':hidden'
,rules: {"product_id_page-0":{"required":true},"name_f":{"required":true,"regex":["^[^=:<>{}()\"]+$",""]},"name_l":{"required":true,"regex":["^[^=:<>{}()\"]+$",""]},"email":{"required":true,"remote":{"url":"\/premium\/ajax?do=check_uniq_email&_url=L3ByZW1pdW0vbG9naW4\/YW1lbWJlcl9yZWRpcmVjdF91cmw9JTJGcHJlbWl1bSUyRnNpZ251cC5waHA="}},"login":{"required":true,"rangelength":["6","32"],"regex":["^([0-9a-zA-Z_][0-9a-zA-Z_ ]+[0-9a-zA-Z_]|[0-9a-zA-Z_]+)$",""],"remote":{"url":"\/premium\/ajax?do=check_uniq_login"}},"pass":{"required":true,"rangelength":["6","32"]},"_pass":{"required":true}}
,messages: {"product_id_page-0":{"required":"Please choose a membership type"},"name_f":{"required":"Please enter your First Name","regex":"Please enter your First Name"},"name_l":{"required":"Please enter your Last Name","regex":"Please enter your Last Name"},"email":{"required":"Please enter valid Email","remote":"--wrong email--"},"login":{"required":"Please enter valid Username. It must contain at least 6 characters","rangelength":"Please enter valid Username. It must contain at least 6 characters","regex":"Username contains invalid characters - please use digits, letters or spaces","remote":"--wrong login--"},"pass":{"required":"Please enter Password","rangelength":"Password must contain at least 6 letters or digits"},"_pass":{"required":"This field is required"}}
//,debug : true
,errorPlacement: function(error, element) {
error.appendTo( element.parent());
}
,submitHandler: function(form, event){form.submit();}
// custom validate js code start
,errorElement: "span"
// custom validate js code end
});
The problem is that sometimes the form submits to the url before the validator fires. I'm suspicious of submitHandler: function(form, event){form.submit();} because I don't understand what the event parameter is doing. In the documentation for jquery validation there's no mention of a second parameter.
Any suggestions for debugging the form are also welcome. Variables to log or other ways to view what's happening. I did set debug:true but it doesn't seem to spit any errors to the console.
The problem is that sometimes the form submits to the url before the validator fires.
It might be because you've specified a non-existant rule. There is no such rule/method called regex. However, there is one called pattern contained within the additional-methods.js file. This is the root cause of your problems. Once the required rule is satisfied, the plugin attempts to evaluate the regex rule and chokes.
I'm suspicious of submitHandler: function(form, event){form.submit();} because I don't understand what the event parameter is doing. In the documentation for jquery validation there's no mention of a second parameter.
If you don't understand what it's doing and it's not in the docs, then why did you put the event argument into your code?
The documentation is correct, there is no second argument. However, having the additional arguments is merely superfluous and will not break anything.
You employ a very unusual code formatting style that makes it difficult to read and troubleshoot.
,submitHandler: function(form, event){form.submit();}
There is no second argument for this callback, so you can remove event.
Since you only have form.submit() within your submitHandler, it's not doing anything different from the default. In other words, remove the entire submitHandler, and after validation the form will submit to the action attribute as per the default.
NOTES:
ignore: ":hidden" is the default behavior, so you don't need to specify it.
It's not necessary to enclose the rule names within quotes.
DEMO: http://jsfiddle.net/1e82p64f/

JavaScript Max Length Validation with Overtype/Insert Key

I am trying to edit some existing JavaScript validation code.
Using the onkeydown event, the code checks that the value in a textbox does not go past a maximum length. I cannot use <input maxlength="value" /> as there may be some formatting characters in the string that I can safely exclude from the maximum length.
The code works fine apart from when the user has pressed the insert key to turn overtype on and they have reached the maximum length. When this occurs if they place the cursor before a character and try to overwrite it the validation thinks that this will go over the limit and doesn't realise that a character will actually be replaced.
This answer states that I cannot detect if overtype is on, but doesn't provide any references. So assuming that I cannot detect overtype, is there anyway in the onkeydown event to detect if a character is going to be replaced.
I am happy with an IE only solution.
Update: onblur is not appropriate as this will let them go many characters over the limit before warning them of the maximum length. I would like to prevent them from going over the limit.
Your handler should look at the entire value and check the length. If the length is legal, return. If not, you can update the value with a substring. You may have to use caret position to determine exactly how to manipulate the string which can be tricky as it's slightly different in IE and other browsers.
This is different from what you have now which is probably preventing keypress when max length is reached. Don't prevent keypress, just trim the resulting string.
I don't think your problem is with the onblur validation, but an event you calling on key press by the sounds of it (eg preventing the user to key any more once they reach the limit) or I have misunderstood.
IF your validation is indeed onblur, you shouldn't have to worry about things like insert/overwrite being enabled, you are only interested in what the value of the input element is once the user has completed their input.
IF you are trying to stop the user if they reach this limit as they type, I would write a function to compute the actual length you are testing. For eg,
function validateMyInput() {
var myInputField = document.getElementById('myInput');
var removeAllExcludedCharsResult = myInputField.value.replace('&','');//exclude &
var totalLength = removeAllExcludedCharsResult.length;
if(totalLength < 500) { //limit of this test is 500
return true;
}
else {
return false;
}
}
Obviously change this function to what you need and maybe make it more generic by passing in the element of the input, max length and array of excluded chars to make it reusable.
UPDATE
I have tested this problem is Chrome and the insert key seems to be ignored. IE on the other hand does overkey. However, it seems page specific, for eg, if i have enabled insert on Page A, it doesn't seem to affect Page B. I found this page which seems to be able to grab the keycode event even when insert has been pressed. It might be due to the following code?
if(window.event) {
event = window.event; //where event is the javascript key event.
}
Either way, the link above seems to have accounted for the problem, hopefully it will have the answer if the above is not correct.
Hope I haven't misunderstood what the problem was and this helped.

Javascript events

I am completely confused here. So I am looking for a solution for the following problem:
I want to trigger some function(for now an alert box) using jQuery on an input field. Conditions are:
Input field always maintains the focus.
Input is fed from a USB device, which acts just like a keyboard input. So for 10 characters, there will be 10 keydown and keyup events.
Once input is filled with 10 characters, respective alert box should pop out.
Now the problem I am facing, how do I find out that input fed in is not equal to 10 characters, so throw an error alert box.(lets say just 5 chars came in input, how do I figure out the final count is 5, because there will be 5 keyup events)
You could show a message underneath/beside the input box instead of popping an alert box.
E.g. on every keyup event, check the string length, and if it's not 10, show that message.
If you really, really have to resort to alert box, you could do a timeout check, e.g. only perform the validation after 1000ms of key event inactivity. This could get very annoying on the user though.
You really have two problems here. One is just understanding the jQuery syntax (see the second part to my answer), and the other is - what is the best way to understand WHEN to throw up an error box.
To answer the second question first, my recommendation would be to not use an alert box to warn the user as they tend to be modal and really interrupt the flow of input. Secondly, as you said - how do you know when the person has stopped "typing." Unless you use some sort of timing mechanism (which is more trouble than it's worth), you don't. My suggestion would be to utilize a "div" within your HTML that shows there is an error UNTIL you reach 10 characters. Once that happens, you can hide the div. (And, of course, the div can be styled to look pretty in the meantime.)
So...how to do this...
Let's assuming your input field has an id of "myField." If you are using jQuery (which is in your tags), you would do something like this.
$(function() {
var keypresses = 0;
$('#myField').keyUp(function () {
keypresses++;
if(keypresses == 10) {
$('#error').hide(); // This is your div error with some error text in it.
// Do other stuff.
} else {
// Display an error.
}
});
Alternatively, if you don't want to use the keypresses variable, you can also use..
if($(this).val().length == 10) { }
The real issue is the fact that you are measuring in key press events, because not all key presses (even when the field has focus) will insert a character into field (for example returnesc). Therefore, you will need to measure the string length in order to validate the code before you start executing functions.
In actuality you don't even need jQuery to accomplish what you need, just bind the function call to a key press event, and only execute the function call if yourstring.length = 10
yourInput.onKeyPress(yourString.length = 10 && yourFunction());
Try -
$('#idofinputfield').keyUp(function () {
var length = $('#idofinputfield').val().length;
if(length <= 10){
alert("less than 10");
}else{
alert("greaterthan 10");
}
});

How to set a focus to an input field in method invoked after onchange() event?

I've got problems with setting focus to an input field after validating it.
I've got two fields: from and to.
<spring:message code="template.fields.label.from"/>:
<mvc:input path="templateFields.selectorRangeFrom"
onchange="validateNumber('templateFields.selectorRangeFrom',true)"/>
<spring:message code="template.fields.label.to"/>:
<mvc:input path="templateFields.selectorRangeTo"
onchange="validateNumber('templateFields.selectorRangeTo',true)"/>
And I've got method validateNumber() which validates the field and returns false if the field is invalid, true otherwise.
However the focus never stays on invalid number, it will always go the next object.
function validateNumber(index,isInteger) {
var object = document.getElementById(index);
var value = object.value;
if (testNumeric2(value,isInteger)==false) {
alert('Please correct the value: ' + value);
object.focus();
object.select();
return false;
}
return true;
}
I have found out that if I add: event.returnValue=false (before returning false), then it works for IE.
But I can't find the solution for Firefox.
setTimeout() allows you to defer the execution of a function for a number of milliseconds - if you use zero, this simply means, "do this as soon as you're done with whatever you're doing now" - handling the event, in your case.
Try this:
if (! /** check field **/) {
/** show error **/
setTimeout((function() { object.focus() }), 0);
}
Basically you would be creating a function that will focus your input box, and then instructing the browser to call it as soon as it's done doing the default handling of the event.
I'm not sure what returning false for onChange is supposed to mean. If you merely wish to re-focus the problem area, I would suggest you do this via a setTimeout() call (you will have to create a closure around your input element).
This way the event handling will be complete when you attempt to focus the text box.
As a side note, I would also suggest you don't use alert() to notify the user of an error, since it is jarring, and can cause a harsh unexpected sound on many Windows systems. Displaying an icon next to, or a red border around the trouble control would probably be a much better way to treat the user.

Categories