I have a client who wants me to punctuate all currency inputs with commas and dollar signs. This means that I have to use a text input instead of a number input, which means that I cannot take advantage of the inbuilt validation that number inputs have, chiefly min, max, step, and simply validating that what the user enters is in fact a numeric string. My idea is therefore to create a text input copy of the actual numeric input, hide the actual one, format the contents of the text input as the user types, and copy them over into the hidden numeric input so that they can be validated and submitted from there. What is the best way with javascript to display any validation errors that might pop up from the hidden number input? I am specifically looking at the constraint validation api:
https://developer.mozilla.org/en-US/docs/Web/API/Constraint_validation
Here's the example html:
<!-- hidden actual input field -->
<input id="real" name="cost" type="number" min="0" max="1000" step=".01" style="display:none;" />
<!-- visible, fake, punctuated input field -->
<input id="punctuated" type="text" />
So I am wanting to find a way to take any validation objects in the DOM for the first input and copy them over to the 2nd. I have tried this so far (see below), but it appears that the validity and validationMessage DOM properties are readonly:
var punctuated = document.getElementById('punctuated');
var real = document.getElementById('real');
punctuated.validationMessage = real.validationMessage;
punctuated.validity = real.validity;
This appears to be the answer:
punctuated.setCustomValidity(real.validationMessage);
I just bound that to the page load, and a click and keyup event for the punctuated input, and it seems to work. So when the user types stuff into the punctuated input, it gets copied over to the real input and validated using the html attributes, and then the click and keyup events pass the validation message to the punctuated input.