You can do this basically like this. Use pattern for a basic validation and validate for an additional validation. It’s not perfect (and free of bugs) yet, but it should give you a good direction.
let input = document.querySelector("#age-height-weight");
function validate() {
let regex = /(d+)-(d+)-(d+)/
let content = regex.exec(input.value);
input.setCustomValidity("");
// This validation is done implicitly using 'pattern' and 'required',
// but you could also do this manually, which would be actually more consistent.
if (!content) return;
// Now the additonal validation, if the pattern basically is fine.
let [all, age, height, weight] = content;
if (age < 16 || age > 99) {
input.setCustomValidity("Invalid age.")
}
if (height < 100 || height > 290) {
input.setCustomValidity("Invalid height.")
}
if (weight < 40 || weight > 200) {
input.setCustomValidity("Invalid weight.")
}
}
input.addEventListener("focusout", validate);
input.addEventListener("focusin", validate);
<form id="my-form">
<input type="text" id="age-height-weight" pattern="d{2}-d{3}-d{2,3}" title="Age (16-99)-Height (100-290)-Weight (40-200)" required>
<button type="submit">Submit</button>
</form>
You can solve this by using the telephone html input instead by using some regex to get the format you want. Here is a snippet of the solution
Note: The pattern tag isn’t supported in Safari 10 or earlier, to support that you’ll want the regex to be done through javascript
var sub = document.getElementById("submit");
var input = document.getElementById("userinfo");
sub.onsubmit = function() {
var args = input.value.split("-");
if (args[0] < 16 || args[0] > 99) { invalidInput("age"); return; }
if (args[1] < 100 || args[1] > 290) { invalidInput("height"); return; }
if (args[2] < 40 || args[2] > 200) { invalidInput("weight"); return; }
console.log(`Age: ${args[0]}, Height: ${args[1]}, Weight: ${args[2]}`);
}
function invalidInput(type) {
console.log(`Input "${type}" was invalid`);
return;
}
<!DOCTYPE html>
<html>
<body>
<form id="submit">
<label for="userinfo">Info:</label>
<input type="text" id="userinfo" placeholder="Age-Weight-Height" pattern="[0-9]{2}-[0-9]{3}-[0-9]{2,3}" title="Three, Three digit numbers, separated by hyphons e.g. 123-123-123"><br><br>
<input type="submit">
</form>
</body>
</html>
I have an number type input field…
I want this format:
Age-Height-Weight
20-180-80
How can I force users input exactly this type and then insert the final result to the input field type=”number” and submit it?
Age — from 16 to 99
Height — from 100 to 290
Weight — from 40 to 200
Then the result, for example 18-170-60 must be sent as one value…
20-180-80 this is text not number. So you can’t do it with number input