I have 2 fields formed with an input element of type text. These fields will contain a number.
Field 1 must be filled with a number that must always be less than field 2.
By means of a button or when changing the value of one of the 2 fields I get an alert in the event that the condition is not met.
I want to replace the alert with a message with the same validation style that is used in Html5 so that it appears in one of the 2 fields in the event that the condition is not met. The message style must respect the same validation styles that different browsers use.
Here is an example for a case where a field validation is invalid:
var input = document.getElementById('campo1');
input.oninvalid = function(event) {
event.target.setCustomValidity('El campo1 debe ser mayor al campo2');
}
How to take advantage of oninvalid or another type of event to relate a condition between 2 fields?
You can achieve what you set out to do using the
setCustomValidity()
HTML5 Restrictions API method .ISSUE
You want to validate 2 elements
input
in such a way that the (numeric) value entered in one of the elements is always less than the (numeric) value entered in the second element.SOLUTION
To solve the problem, we need to decide when to perform the validation. We can validate at the time of submitting the form when the button is clicked
submit
, or we can validate at the time of writing the values in each of the elements.My recommendation is to do it when you click the button
submit
. Since this will give us more flexibility and also avoid dealing with the case where a value is being entered in field 1 and no value has been entered in field 2 yet, or vice versa.We also need to decide which field to put the constraint on, since we can't put it on both (bad design practice).
One way to implement the above would be as follows:
As you can see, it's easy to use or implement custom validation messages, what you need to keep in mind is the order in which you want to validate the fields. Good design maintains consistency between events and user actions.
A working example of the above could be the following:
Entering a smaller number in the second
input
and clicking the button will highlight the element in red as invalid, using the styles provided by the browser. If you hover your mouse over theinput
invalid element, you'll see the custom validation message.I hope it is what you were looking for. There are many ways to perform validation, it all depends on the logic you want to apply and how complex your form is.
You can create a custom validation for the event
onblur
of the elementinput
, however, you must take into account the case in which the other elementinput
does not yet have a value and if it does, that it be a valid numeric value.