"Bubble" validation message on non-form element - javascript

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.

Related

Trouble sending JavaScript into <input type="date"> calendar

Goal: Attempting to automate a calendar on Chrome using Selenium(Python + behave).
The issue: The date is only being set when actually clicked through the calendar. Passing a value via JavaScript is not working.
Note: According to docs the inputs should allow users to send input in with keys by default but that doesn't even work. It does not accept keyboard input at all.
Problem Walkthrough
This is the original input fields. The div class they are contained in is inside a #shadow-root
(open):
Ignoring the Python. I will try and change the values with some simple JavaScript in the Chrome Dev Tools console:
x = document.querySelector("#class > something").shadowRoot.querySelector("div > div > input[type=date]:nth-child(5)") #Select input for From Date
x = "2022-05-12"
y = document.querySelector("#class > something").shadowRoot.querySelector("div > div > input[type=date]:nth-child(5)") #Select input for To Date
y = "2022-06-12"
After sending in the new values and clicking search. It does not recognize the values as being entered:
However, when manually selected through the calendar:
The dates are accepted and as inputs:
The HTML for the calendar is:
<input type="date" min="2022-01-01" max="2022-07-19">
Clearly. The JavaScript alone does not seem to be enough. If you use the same method above on this calendar it will work. However, on the calendar I am attempting this JS method will not work for some reason. Also, I cannot get Selenium to click and open the calendar on its own for some odd reason.
Solution: Manually trigger the event (Source)
let element = document.getElementById(id);
element.dispatchEvent(new Event("change")); // or whatever the event type might be
dispatchEvent() Documentatio
Event() Documentation

Javascript to "copy in real time" some fields from a form to another form (with different input names)

I'm trying to write a function to copy some fields (in real time) from a specific form, to another form
I try to be more specific:
I have 2 forms
- The first form is the one the user will fill in.
- The other form is hidden.
When the user will fill the first form, the second form (hidden) will be filled by the same informations.
Some fields are automatically filled by some calculations, so I can't use keyup/keypress or "click" to start the function
I wrote something like this, but it doesn't work
$(function(){
var form1 = $('#form1'),
form2 = $('#form2');
$('#fieldname_form1').change(function(){
$('input[name="inputname2"]', form2).val(function(){
return $('input[name="inputname1"]', form1).val();
});
});
});
You can copy in real time using the keyup function, something like this. Otherwise, when you say
Some fields are automatically filled by some calculations
What do you mean? These calculations are made by you using JS or what? Because, if you are using JS you can fill the two fields at the same time when you make the calculations.
this works for me...
$(function() {
$('#i1').change(function(evt) {
$('#i2').val(evt.target.value);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" name="name1" id="i1" />
</form>
<form>
<input type="text" name="name2" id="i2" />
</form>
The change event is fired after the element has lost the focus. For the "user editable" elements you should use keyup (for the textbox) and change for the drop down elements.
On the other hand, for the fields filled automatically, you don't have any nice and clean solutions. I can think in two options:
If the calculations trigger is always the user changing some value, you could copy every form value after that happens.
(very bad option, but it would still work) You could be constantly checking for changes in every element and copying them using setInterval function.
As a side note
As well as your code should work, there is a simpler way to do it:
$('#fieldname_form1').change(function(){
var value = $('input[name="inputname1"]', form1).val();
$('input[name="inputname2"]', form2).val(value);
});
This should work -
$(function() {
var form1 = $('#form1'),
form2 = $('#form2');
$('#fieldname_form1').change(function() {
$('input[name="inputname2"]', form2).val($(this).val());
});
});

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

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;
}
}

Using depends with the jQuery Validation plugin

I've got a form with a bunch of textboxes that are disabled by default, then enabled by use of a checkbox next to each one.
When enabled, the values in these textboxes are required to be a valid number, but when disabled they don't need a value (obviously). I'm using the jQuery Validation plugin to do this validation, but it doesn't seem to be doing what I expect.
When I click the checkbox and disable the textbox, I still get the invalid field error despite the depends clause I've added to the rules (see code below). Oddly, what actually happens is that the error message shows for a split second then goes away.
Here is a sample of the list of checkboxes & textboxes:
<ul id="ItemList">
<li>
<label for="OneSelected">One</label><input id="OneSelected" name="OneSelected" type="checkbox" value="true" />
<input name="OneSelected" type="hidden" value="false" />
<input disabled="disabled" id="OneValue" name="OneValue" type="text" />
</li>
<li>
<label for="TwoSelected">Two</label><input id="TwoSelected" name="TwoSelected" type="checkbox" value="true" />
<input name="TwoSelected" type="hidden" value="false" />
<input disabled="disabled" id="TwoValue" name="TwoValue" type="text" />
</li>
</ul>
And here is the jQuery code I'm using
//Wire up the click event on the checkbox
jQuery('#ItemList :checkbox').click(function(event) {
var textBox = jQuery(this).siblings(':text');
textBox.valid();
if (!jQuery(this).attr("checked")) {
textBox.attr('disabled', 'disabled');
textBox.val('');
} else {
textBox.removeAttr('disabled');
textBox[0].focus();
}
});
//Add the rules to each textbox
jQuery('#ItemList :text').each(function(e) {
jQuery(this).rules('add', {
required: {
depends: function(element) {
return jQuery(element).siblings(':checkbox').attr('checked');
}
},
number: {
depends: function(element) {
return jQuery(element).siblings(':checkbox').attr('checked');
}
}
});
});
Ignore the hidden field in each li it's there because I'm using asp.net MVC's Html.Checkbox method.
Using the "ignore" option (http://docs.jquery.com/Plugins/Validation/validate#toptions) might be the easiest way for you to deal with this. Depends on what else you have on the form. For i.e. you wouldn't filter on disabled items if you had other controls that were disabled but you still needed to validate for some reason. However, if that route doesn't work, using an additional class to filter on (adding and removing with your checkboxes) should get you to where you want to go, but easier.
I.e.
$('form').validate({
ignore: ":disabled",
...
});
Usually when doing this, I skip 'depends' and just use the required jQuery Validate rule and let it handle the checking based on the given selector, as opposed to splitting the logic between the validate rules and the checkbox click handler. I put together a quick demo of how I accomplish this, using your markup.
Really, it boils down to required:'#OneSelected:checked'. This makes the field in question required only if the expression is true. In the demo, if you submit the page right away, it works, but as you check boxes, the form is unable to submit until the checked fields are filled with some input. You could still put a .valid() call in the checkbox click handler if you want the entire form to validate upon click.
(Also, I shortened up your checkbox toggling a bit, making use of jQuery's wonderful chaining feature, though your "caching" to textBox is just as effective.)
Depends parameter is not working correctly, I suppose documentation is out of date.
I managed to get this working like this:
required : function(){ return $("#register").hasClass("open")}
Following #Collin Allen answer:
The problem is that if you uncheck a checkbox when it's error message is visible, the error message doesn't go away.
I have solved it by removing the error message when disabling the field.
Take Collin's demo and make the following changes to the enable/disable process:
jQuery('#ItemList :checkbox').click(function()
{
var jqTxb = $(this).siblings(':text')
if ($(this).attr('checked'))
{
jqTxb.removeAttr('disabled').focus();
}
else
{
jqTxb.attr('disabled', 'disabled').val('');
var obj = getErrorMsgObj(jqTxb, "");
jqTxb.closest("form").validate().showErrors(obj);
}
});
function getErrorMsgObj(jqField, msg)
{
var obj = {};
var nameOfField = jqField.attr("name");
obj[nameOfField] = msg;
return obj;
}
You can see I guts remove the error message from the field when disabling it
And if you are worrying about $("form").validate(), Don't!
It doesn't revalidate the form it just returns the API object of the jQuery validation.
I don't know if this is what you were going for... but wouldn't changing .required to .wasReq (as a placeholder to differentiate this from one which maybe wouldn't be required) on checking the box do the same thing? If it's not checked, the field isn't required--you could also removeClass(number) to eliminate the error there.
To the best of my knowledge, even if a field is disabled, rules applied to it are still, well, applied. Alternatively, you could always try this...
// Removes all values from disabled fields upon submit
$(form).submit(function() {
$(input[type=text][disabled=disabled]).val();
});
I havent tried the validator plugin, but the fact that the message shows for a splitsecond sounds to me like a double bind, how do you call your binders? If you bind in a function try unbinding just before you start, like so:
$('#ItemList :checkbox').unbind("click");
...Rest of code here...
Shouldn't validate the field after disabling/enabling?
jQuery('#ItemList :checkbox').click(function(event) {
var textBox = jQuery(this).siblings(':text');
if (!jQuery(this).attr("checked")) {
textBox.attr('disabled', 'disabled');
textBox.val('');
} else {
textBox.removeAttr('disabled');
textBox[0].focus();
}
textBox.valid();
});
I had the exact same problem.
I solved this by having the radio-button change event handler call valid() on the entire form.
Worked perfect. The other solutions above didn't work for me.

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