Mute HTML validation message while typing - javascript

Steps to reproduce the issue:
Set an input of type email / phone
Set the input as required
Hit form submit on the wrong pattern for email
The HTML validation message should be now visible.
Keep entering text into the input box
On entering the text in the input box after the validation message has been kicked in, the validation message persists and gets displayed on every keystroke.
I even tried setting setCustomValidity("") on keyup event but that does not help either.
Here is an example fiddle.
Here is a gif of the problem:
You can see that until I add #gmail.com to the email input, it keeps showing the HTML validation.
Any help would be appreciated.
Source code for the same.
HTML
<form>
<p>
<label for="t2">What's your e-mail?</label>
<input id="email" type="email" id="t2" name="email" required>
</p>
<p>
<button>Submit</button>
</p>
</form>
JS
$("#email").on("keyup", function (e) {
if (e.target.value.lenth !== 0) {
e.target.setCustomValidity("");
}
});

When the user presses enter and the input validation fails, that input fires an invalid event. So, you can add an invalid handler to customize (and possibly prevent) the resulting behavior. The invalid event does not get triggered by further inputs of normal characters, but the invalid pop-up will keep appearing as long as the input remains invalid and focused. When the input is unfocused (blurred), the validation pop-up will disappear. It will re-appear only after the user re-focuses the input and presses enter when the input text is still invalid.
So, one possible solution is to add an invalid listener that keeps track of whether the error pop-up is showing or not. Then, add a keydown listener that checks if the pop-up is showing. If the pop-up is showing, blur and then focus the element, so as to make the pop-up disappear until the next time the user presses enter:
let errorShowing = false;
$("#email")
.on('invalid', (e) => {
errorShowing = true;
})
.on("keydown", function(e) {
if (!errorShowing) return;
setTimeout(() => {
this.blur();
this.focus();
});
errorShowing = false;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form">
<label for="t2">What's your e-mail?</label>
<input id="email" type="email" id="t2" name="email" required>
</form>

Related

How does onchange and onkeyup work in javascript?

I was trying to validate a password field when I found the javascript code on the net. Can someone please explain when is the "onchange" fired and why does the code not work when I replace onkeyup with onchange (last 2 lines in javascript code)
function validatePassword(){
if(password.value != confirm_password.value) {
confirm_password.setCustomValidity("Passwords Don't Match");
} else {
confirm_password.setCustomValidity('');
}
}
password.onchange = validatePassword;
confirm_password.onkeyup = validatePassword;
<div class="password" id="password-fields" style="display:none">
Password: <input type="password" name="password" class="password" id="password"><br>
Confirm Password: <input type="password" name="password" class="password" id="confirm-password">
</div>
<div> <input type="submit" name="submit"> </div>
</form>
The change event occurs when you leave an input field after having changed its value. It doesn't fire immediately as the user changes the value, only when they've finished, which is detected by them using the keyboard or mouse to select a different element on the page.
The keyup event occurs after every keystroke. This allows you to take action while the user is typing.
The onChange event occurs when the value is assigned to the field, which is usually when the field loses focus.
The onKey events are bound to the keypress, meaning, they are triggered by the key itself and not related to the value assignment of the field.
The onKeyUp event will only fire when the user physically stops pressing the key (when the key goes "up").
You can test the behavior here.

Changing focus from one input to the next with a barcode scanner

I am using a barcode scanner to enter data into input fields on a webpage. I set up the form and autofocus on the first input field. When the first barcode is entered into the first input field I would like focus to jump to the next input field. However, as soon as I enter the first barcode the form 'submits'. Here is the html I am using:
<form id="barcode1" name="barcode" method="Post" action="#">
<div>
<label for="S1">Barcode 1 </label>
<input id="S1" class="bcode" type="text" name="S1" autofocus/>
<label for="S2">Barcode 2 </label>
<input id="S2" class="bcode" type="text" name="S2" />
<label for="S3">Barcode 3 </label>
<input id="S3" class="bcode" type="text" name="S3" />
</div>
<p><input type="submit" name="Submit" value="Submit"></p>
</form>
I have tried solutions from similar SO questions here and [here] (http://jsfiddle.net/davidThomas/ZmAEG/), but they don't seem to work.
Ideally I would like to have a solution something like this (the second link above), so please let me know where or why this is not working and what I can do to fix it.
$('form').on('keypress','input',function(e){
var eClassName = this.className,
index = $(this).index('.' + eClassName) + 1;
if (e.which === 13){
e.preventDefault();
$('input.' + eClassName)
.eq(index)
.focus();
}
});
You need to return false in order to prevent the enter key from submitting the form.
The answer to this question will help you: Prevent form submission with enter key
//Press Enter in INPUT moves cursor to next INPUT
$('#form').find('.input').keypress(function(e){
if ( e.which == 13 ) // Enter key = keycode 13
{
$(this).next().focus(); //Use whatever selector necessary to focus the 'next' input
return false;
}
});
No need to make any changes to your bar scanner.
If your barcode scanner is a keyboard wedge, you should be able to configure the trailing character to a TAB.
It seems like, by default, your scanner is trailing with an ENTER (carriage return).
Another option would be to also check for a LF (decimal 10) in your javascript code.
Looks like your function will never get called because browser submits the form on Enter. You may have to suppress submit until all fields are filled (or some other condition) by intercepting submit event first.
$( "form" ).submit(function( event ) {
if(/*all req. fields are filled -> submit the form*/)
$(this).submit();
event.preventDefault();
});

Avoid auto submit form after scanning thru barcode scanner

HTML
<form action="die_issue_process.php" id="form" method="post" autocomplete="off">
<input type="text" name="item_name[]" />
<input type="button" name="add_item" value="Add More" onClick="addMore();" />
<input type="submit" id="Search" name="Search" value="Search" />
Javascript code:
function addMore() {
$("<DIV>").load("input.php", function() {
$("#product").append($(this).html());
});
}
Friends in this form I have single text box and add button to add text box according to the need. Here in this form I'm giving input thru a BAR CODE reader so once the bar-code is scanned the form gets automatically submitted but my requirement is it should be submitted only after giving the submit button
Note: my form gets auto submitted on first scan of input box itself.
Well, a barcode scanner, reads the barcode and submits automatically!
So I think you better change your input with the type "submit" to a button
<input type="button" id="Search" name="Search" value="Search" />
You can consider a barcode scanner as a very specialised keyboard. If you test your barcode scanner whilst in a text editor. You will see they just very quickly enter the string that the barcode represents, followed by a carriage return.
These are indistinguishable from the keystrokes required to manually perform the same operation, using the keyboard.
If you are focused on a text field in a form, pressing enter will often submit the form.
To prevent the enter key from submitting a form on a text field, you can kill that keystroke with an event handler, for example:
(function() {
var textField = document.getElementById('textFieldId');
if(textField) {
textField.addEventListener('keydown', function(mozEvent) {
var event = window.event || mozEvent;
if(event.keyCode === 13) {
event.preventDefault();
}
});
}
})();
If the scanner is feeding to a textbox, start your form with your submit button hidden. Only visiable it once the textbox has data input. this can be done by javascript..

Input validation on bootstrap html form with javascript addevent listener

i'm having difficulties with validating the value of a text box element in the html with the addeventlistener in my javascript. It does not properly validate my input in the following ways :
1)Showing "field is empty" even when I have values in that textbox.
2)Only validates when i click submit. <-- (how do i perform the validation as the user clicks out of the text box? )
The following is the relevant html code (with bootstrap classes):
<div class ="col-lg-8">
<div class="form-group">
<label for="inputfirstName" class="col-sm-2 control-label">First Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputfirstName"
placeholder="Enter First Name" />
</div>
</div>
The following is the relevant javascript code to valdiate that the First name text box field is not empty and if it is it should return a custom validation error
window.addEventListener('load',init);
function init()
{
var firstname = document.getElementById("inputfirstName");
firstname.addEventListener('onmouseclick',validateFirstname(firstname));
}
function validateFirstname(e){
var checker = e.value;
if (checker == ""){
e.setCustomValidity("This field must not be blank !");
}
}
I am not really sure, when you want to validate your input.
Currently, you are listening to the user clicking into your textbox and performing the validation in that very moment.
However, since you are only adding the validation error with your call to e.setCustomValidity it won't display until you post your form. This is by design of setCustomValidity. This is explained in more details here: How to force a html5 form validation without submitting it via jQuery
To validate your textbox after the user entered his text, you would use the input and change events. Input fires when the user types something into your textbox, change after the user leaves the textbox. To trigger the validation regardless of the user ever focusing on that field, you also have to set your input to "required". Then to display your message instead of the standard required message of HTML5 you also have to add the invalid event to your event listeners. You can find a more refined answer here with the complete code on how to accomplish this here: Set custom HTML5 required field validation message
<input type="text" class="form-control" id="inputfirstName"
placeholder="Enter First Name" required="required"/>
window.addEventListener('load',init);
function init()
{
var firstname = document.getElementById("inputfirstName");
firstname.addEventListener('input',validateFirstname(firstname));
firstname.addEventListener('change',validateFirstname(firstname));+
}
function validateFirstname(e){
var checker = e.value;
if (checker == ""){
e.setCustomValidity("This field must not be blank !");
}
else{
e.setCustomValidity("");
}
}

Custom HTML5 form validation not showing custom error initially

Basic HTML5 form with custom validation. If the submitted value is not a number, the browser should display the error message "Field must be an number." If you enter "abc" and press submit (or hit enter) the field is marked as invalid, but the error message does not appear. Press submit again (or hit enter) and it will show the message. This double-submit behavior appears on latest versions of Firefox, Chrome, Safari, and IE on Windows and OS X. You will notice that the default "this field is required..." message appears upon the first submission and does not exhibit the odd behavior.
http://jsfiddle.net/6gsr3r4b/
As an aside, I am well aware that this validation will not work in older versions of IE and that the input field could have a type of number that would automatically complete this validation; this is simplified example of my problem for demonstration purposes only.
Javscript
var form = document.getElementById("form");
var field = document.getElementById("field");
form.onsubmit = validateForm;
function validateForm() {
if(isNaN(field.value)) {
field.setCustomValidity("Field must be a number.");
} else {
return true;
}
return false;
}
HTML
<form id="form">
<label for="field">Favorite number</label>
<input type="text" id="field" required>
<input type="submit">
</form>
After setting the validity message, you need to call element.reportValidity() to make it show up.
setCustomValidity(message)
Sets a custom error message string to be shown to the user upon submitting the form, explaining why the value is not valid — when a message is set, the validity state is set to invalid. To clear this state, invoke the function with an empty string passed as its argument. In this case the custom error message is cleared, the element is considered valid, and no message is shown.
reportValidity()
Checks the element's value against its constraints and also reports the validity status; if the value is invalid, it fires an invalid event at the element, returns false, and then reports the validity status to the user in whatever way the user agent has available. Otherwise, it returns true.
You also need to use event.preventDefault() on the form submission event whenever the input is invalid, so that the form submission doesn't go through.
Here is an example:
var form = document.getElementById('form');
var field = document.getElementById('field');
form.onsubmit = validateForm;
/* this is the function that actually marks the field as valid or invalid */
function validateForm(event) {
if (isNaN(field.value)) {
field.setCustomValidity('Field must be a number.');
field.reportValidity();
event.preventDefault();
}
field.setCustomValidity('');
}
<form id="form">
<label for="field">Favorite number</label>
<input type="text" id="field" required />
<input type="submit" />
</form>
You can also use the HTML5 pattern attribute to do most form validation without JavaScript, or augmented with JavaScript to set custom error messages.
Pattern: A regular expression that the control's value is checked against. The pattern must match the entire value, not just some subset. Use the title attribute to describe the pattern to help the user. This attribute applies when the value of the type attribute is text, search, tel, url or email; otherwise it is ignored. The regular expression language is the same as JavaScript's. The pattern is not surrounded by forward slashes.
<form id="form">
<label for="field">Favorite number</label>
<input type="text" id="field" pattern="\d*" title="Field must be a number." required />
<input type="submit" />
</form>

Categories

Resources