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>
Related
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>
I am using Angular 2 and I have a form with input as follows (simplified for readability's sake):
<input class="body-text1" type="text" [(ngModel)]="model.name" name="name" required minlength="1">
<!--more, similar inputs -->
I have my own angular validation, but the first input field gets a popup that is relevant to the input. For example, a plain text required input will receive a popup that says "Please fill out this field." while an input marked with type=email will say something like "Invalid email, must have #" (I forget the exact email popup text).
As far as I can tell, I did not add these popups in. I have tried adding formnovalidate / novalidate as attributes to the inputs based on a question that looked similar but it did not help.
You might need to add novalidate attribute to your form to prevent Browser default behaviour.
<form novalidate>
This popup shows because the required attribute is on the element. If you remove this, the popup will be gone, so will the validation be though.
When validating an email field [name=bar] in a form #foo, I want to switch validation of that field on and off, in relation to a checkbox.
Reading the docs, github issues and stackoverflow answers, I thought setting data-parsley-required="false" and/or data-parsley-validate="false" would be enough.
But it turns out, that all other constraints, like email, min-lenght, max-length are still validated and the input field still validates to an error condition. I would prefer it to validate to success or not at all.
<form id="foo">
<input name="bar"
maxlength="40"
value=""
class="form-control"
data-parsley-validate="false"
data-parsley-required="false"
type="email"
data-parsley-minlength="5"
data-parsley-trigger="input keyup change"
data-parsley-error-message="something is wrong">
</form>
See https://jsfiddle.net/88obg0sj/9/
So how is it possible to turn off field validation in way, it can be re-activated again?
You should tweak the excluded option, for example by adding ", [data-parsley-validate="false"]" to it.
You can follow this way:-
//destroy parsley
$('form').parsley().destroy();
//set required attribute on input to false
$('input').attr('data-parsley-required', 'false');
//reinitialize parsley
$('form').parsley();
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("");
}
}
For instance in this example;
<form>
<input type="email" name="email" id="useremail" placeholder="Email Address" required> <br>
<input type="tel" name="phone" id="userphone" placeholder="Phone Number" maxlength="10" required> <br>
<input type="submit" id="sidebarformsubmit" value="Submit">
</form>
Is it possible to somehow/somewhere be able to identify that the user has inputed something in EITHER the email or phone number field. So that on submit it doesn't show "this is required".
Reword: Can at least one of the form inputs be mandatory, both is allowed as is one or the other but not none. In the above example, the user needs to have at least one form of communication whether that be phone number or email. They can have both however, but not none.
If so, how would you go about this?
You can easily capture the change events from the inputs and set the required attribute accordingly.
Like this:
var email = document.getElementById('useremail'),
phone = document.getElementById('userphone');
function onchange(){
email[phone.value?'removeAttribute':'setAttribute']('required','required');
phone[email.value?'removeAttribute':'setAttribute']('required','required');
}
email.addEventListener('change',onchange);
phone.addEventListener('change',onchange);
jsfiddle
Is it possible to somehow/somewhere be able to identify that the user has inputed something in EITHER the email or phone number field. So that on submit it doesn't show "this is required".
1) No. If you use HTML5 required on a field then that field is required. There is no way to specify interdependence.
2) Yes. You can use client-side javascript validation, generally hooked to a form submit event to do as-complex-as-you-like validation. Prevent the submit by returning false from the event handler if you don't pass validation.
3) Yes. You can do validation that can be as complex as necessary on the server when you have received the submitted form, and return directly to the form if something is wrong.
3b) You Must do validation on the server, even if you have great client-side javascript validation, otherwise I will buy things from your site for one penny. You must not trust the client.