How to manually show an HTML validation message from a JavaScript function? - javascript

I want to know if there is any way to programmatically show a HTML validation error, using a JavaScript function.
This is useful for scenarios where email duplication has to be checked. For example, a person enters an email, presses the Submit button, and then has to be notified that this email is already registered or something.
I know there are other ways of showing such an error, but I wanted to display it in the same way as how the validation error messages are shown (e.g. invalid email, empty field, etc.).
JSFiddle: http://jsfiddle.net/ahmadka/tjXG3/
HTML Form:
<form>
<input type="email" id="email" placeholder="Enter your email here..." required>
<button type="submit">Submit</button>
</form>
<button id="triggerMsg" onclick="triggerCustomMsg()">Trigger Custom Message</button>
JavaScript:
function triggerCustomMsg()
{
document.getElementById("email").setCustomValidity("This email is already used");
}
The above code sets the custom message, but its not automatically shown. It's only shown when the person presses the submit button or something.

You can now use the HTMLFormElement.reportValidity() method, at the moment it's implemented in most browsers except Internet Explorer (see Browser compatibility at MDN). It reports validity errors without triggering the submit event and they are shown in the same way.

var applicationForm = document.getElementById("applicationForm");
if (applicationForm.checkValidity()) {
applicationForm.submit();
} else {
applicationForm.reportValidity();
}
reportValidity() method will trigger HTML5 validation message.

This question was asked over a year ago, but it's a good question that I recently encountered as well...
My solution was to use JavaScript to create an attribute (I went with "data-invalid") on the <label> of each <input>, <select> and <textarea> containing the validationMessage.
Then some CSS...
label:after {
content: attr(data-invalid);
...
}
... displays the error message.
Limitations
This only works provided each element has a label. It will not work if you put the attribute on the element itself, because <input> elements cannot have :after pseudo elements.
Demo
http://jsfiddle.net/u4ca6kvm/2/

As mentoned by #Diego you can use form.reportValidity();
To support IE and Safari include this polyfill, it just works:
if (!HTMLFormElement.prototype.reportValidity) {
HTMLFormElement.prototype.reportValidity = function() {
if (this.checkValidity()) return true;
var btn = document.createElement('button');
this.appendChild(btn);
btn.click();
this.removeChild(btn);
return false;
}
}

Related

How to display "Please fill out this field" for all empty and required fields in html form?

I have a form as shown in the fiddle https://jsfiddle.net/vrn7zx5h/3/ in which I want to show the warning sign "Please fill out this field" at the same time for all unfilled required fields.
I found the answer on SO (as shown below) but i am not sure how to integrate with the fiddle.
function checkName(val){
if(/^[^-\s][\w\s]+$/.test(val)){
return true;
}else{
if(val.length != 0){
return false;
}
}
}
Problem Statement:
I am wondering what changes I should make in the fiddle so that the above pasted SO answer works with the fiddle.
Here is a JS fiddle that will show all error at one time. It is just barebone and not fancy. You'll need to make it fancy on your own. I also disabled the built-in validator as well with novalidate in the form tag.
https://jsfiddle.net/6kxc9hmq/1/
FYI: I also did not put in the functionality to hide the error message on next run, if the input now satisfies the condition.
Basically, I attached a submit event handler to the form and if the validator returned false, I told the form to not submit. Works only on IE9+ (I think) all the other browsers are usually fine with this method. The validator is basically just checking if the value of the input met the condition that I specified.
document.getElementById('form').addEventListener('submit', function(e) {
if(!validate())
e.preventDefault();
});
I think it should look like this, if I understand what you mean
<form action="">
Username: <input type="text" name="usrname">
Password: <input type="password" name="Password">
<input type="submit">
</form>
<p><strong>Note:</strong> The required attribute of the input tag is not
supported in Internet Explorer 9 and earlier versions.</p>
<script>
// append the listeners
document.forms[0].addEventListener('submit', function(evt){
if([
checkName(this.querySelector('[name="usrname"')),
checkName(this.querySelector('[name="Password"'))
].some((v)=>v)) {
evt.preventDefault()
}
})
// check is empty, then notify
function checkName(element){
// if you just have to check if is empty, this is enough
if(element.value) {
return
}
notify(element)
return true
}
// print the message
function notify(element) {
if(element.nextElementSibling.classList.contains('notify')) {
return;
}
element.parentNode.insertBefore(
Object.assign(document.createElement('p'),
{
className: 'notify',
innerHTML: 'Please fill out this field for all empty and required fields'
}
), element.nextSibling)
}
</script>
In your form, add empty divs after each input element. And you can conditionally display messages in the div in your validation. E.g if(name ==‘ ‘){div.innerHTML = ‘please enter your name’}
The required Attribute
Add the required attribute to your form.
The required attribute tells the browser to only submit the form if the field in question is filled out. Obviously, this means that the field can’t be left empty, but it also means that, depending on other attributes or the field’s type, only certain types of values will be accepted.

how to check if input field is empty on submit [duplicate]

This question already has answers here:
Check if inputs are empty using jQuery
(22 answers)
Closed 9 years ago.
I'm using jQuery so i wonder how can i show error message after i click submit button only if an input field is empty.
Below the code my simple form how to apply to it.
<form id="myid" name="myid" method="post" action="hook.php">
name : <input type="text" name="name" id="name">
age : <input type="text" name="age" id="age">
<input type="submit" id="submit" name="submit" value="Save" />
</form>
I would like to show error like this
As someone has already mentioned, you should probably look to use an external library for validation. That said, this seems like it might work (see JSFiddle):
var $form = $("#myid"),
$errorMsg = $("<span class='error'>This field is required..!!</span>");
$("#submit").on("click", function () {
// If any field is blank, we don't submit the form
var toReturn = true;
$("input", $form).each(function () {
// If our field is blank
if ($(this).val() == "") {
// Add an error message
if (!$(this).data("error")) {
$(this).data("error", $errorMsg.clone().insertAfter($(this)));
}
toReturn = false;
}
// If the field is not blank
else {
// Remove the error message
if ($(this).data("error")) {
$(this).data("error").remove();
$(this).removeData("error");
}
}
});
return toReturn;
});
You can use event.preventDefault to stop the default action happening. Then check your condition, display errors if the condition fails and submit the form if not.
$("#submit").click(function(event) {
event.preventDefault();
if($(this).val().length === 0) {
// display some error
} else {
$("#myid").submit();
}
});
Really I advice you to use some frameworks for form validation. Because that's the common task and it was already done 100000 times before. There are plenty of it, for example Parsley or Jquery plugin, but there are a lot of others which is simple and easily maintainable, just google 'javascript form validation'
Why is already implemented code better than custom in that case: 1) It already written, tested and working, 2) You almost never need only single validation, and really to validate form for several parameters could be a challenge and could lead to a big amount of validation code 3) framework is DRYer and a really a lot of other stuff.
I also advise you to use validation framework because you need more validation for different field. Use MooTools Floor this is most reliable framework for validation.
MooTool Floor
You can use the HTML5 required='required' option in the input tag...

"Bubble" validation message on non-form element

I have some elements on a page and I want to make use of the nice bubble style messages such as described here HTML5 form validation. It seems that to use them it is required they are within a form element and they only can be used on validation once the form is attempted to be submitted.
Taking from the linked example, I want to know how to get the following to work as described (i.e for this example pop a bubble message if the user sets a time before now)
Fiddle for this: My attempt without form
<body>
<label>
Arrival Date:
<input id="arrivalDate" type="date" onchange="dateChanged()" />
</label>
<input type="button" value="Test Reservation"></input>
<script type="text/javascript">
function dateChanged(e){
var arrivalDate = document.getElementById("arrivalDate");
var value = new Date(arrivalDate.value);
if (value < new Date()) {
arrivalDate.setCustomValidity("Arrival date must be after now!");
} else {
arrivalDate.setCustomValidity("");
}
arrivalDate.checkValidity();
}
</script>
</body>
Specifically in my case I have 2 KendoUI DateTimePickers being used to select the time range which is used to display information dynamically on the page. I'd like if I could use these bubble messages if the user tries to make the start time after the end time.
There's no way to manually trigger the validation. Using .checkValidity() will only return true/false if the context of what your checking is valid or not, i.e. if you did form.checkValidity() it will check if all form elements are valid, or input.checkValidity() only check the validity of that single element.
The only way to trigger the validation is on submit. You can simulate this by having a submit button and calling the click function.
if (!arrivalDate.checkValidity())
{
document.getElementById('submit_reservation').click();
}
Fiddle: http://jsfiddle.net/QGpQj/3/
Note: I've added window.dateChanged = .... because of your inline event listener. You really should be using .addEventListener or, ideally, jQuery for this to add backwards compatability support for those non-supported browsers.

HTML5 Form Validation

I have two major problem regarding HTML5 form validation.
1- I use this code to change the validation message of inputs
$$('INPUT').each(function(input)
{
input.oninvalid = function(event)
{
event.target.setCustomValidity('');
if (!event.target.validity.valid) event.target.setCustomValidity('Please Fill');
};
}
There's a big problem with this method. As the form is submitted if the input is invalid, an error message is attached to it. So it wouldn't validate on new input. Even after correction and submitting again it won't let the form get submitted because the message is still attached. so event.target.setCustomValidity('') will remove the message and form needs another submit. two submit after correction.
I couldn't find a way to correct this behavior.
2-How can I hide or disable these tooltips totally but still use form validation. Sometimes I want to use css invalid and valid pseudo classes, but these tips are still displayed.
I find formnovalidate on submit button and then I can check validity.valid of each inputs manually before submitting. any better idea?
In terms of question 1:
I had an input
<input name="VoucherCode" id="VoucherCode" type="text" pattern="(1[0-9]{9})|(2[0-9]{9})" value="">
And improved the default message
$("#VoucherCode").on("invalid", function (event) {
event.target.setCustomValidity('The format of Voucher Code is not correct.')
});
But this had the same problem you encountered: if the user gets the first attempt wrong, a correct response still show the invalid pattern message.
I fixed this based on #Pointy's suggestion:
$("#VoucherCode").on("invalid", function (event) {
event.target.setCustomValidity('The format of Voucher Code is not correct.')
}).bind('blur', function (event) {
event.target.setCustomValidity('');
});
(a bit late) but the solution could be around there!
What happen:
Since you customize the error message event.target.setCustomValidity("...") the property in the element.validity.customError is true ; the reportValidity with always return false and the submit wouldn't be valid
What I did?
When the User change the input (event.on Change) - I set up back the default error message event.target.setCustomValidity(''); this will tells the Browser to keep working without a custom error

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