Combine multiple values into a single input in the number field

I have a number type input field...

What I am looking for is:

Age-Height-Weight

20-180-80

Is there a way to ensure that users input data in this exact format and then have the final result inserted into the input field with type="number" and submitted?

Age should be between 16 and 99, Height between 100 and 290, Weight between 40 and 200.

The final result, such as 18-170-60, needs to be submitted as a single value...

Answer №1

One way to approach this is by using a pattern for basic validation and an additional validate function for further validation checks. While it may not be flawless and completely bug-free, it can certainly point you in the right direction.

let input = document.querySelector("#age-height-weight");

function validate() {
  let regex = /(\d+)-(\d+)-(\d+)/
  let content = regex.exec(input.value);
  input.setCustomValidity("");
  
  // The initial validation is automatically handled through 'pattern' and 'required', 
  // however, manual confirmation would provide more consistency.
  if (!content) return;
  
  // Proceed with additional validation if the pattern seems valid.
  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>

Answer №2

To tackle this problem, consider utilizing the telephone HTML input and employing regex to achieve the desired format. Below is a portion of the suggested solution:

Please note: The pattern tag lacks support in Safari version 10 or earlier. To cater to this, it's advisable to execute the regex algorithm using JavaScript.

var submit = document.getElementById("submit");
var userInput = document.getElementById("userinfo");

submit.onsubmit = function() {
    var arguments = userInput.value.split("-");
    
    if (arguments[0] < 16 || arguments[0] > 99) { invalidInput("age"); return; } 
    if (arguments[1] < 100 || arguments[1] > 290) { invalidInput("height"); return; }
    if (arguments[2] < 40 || arguments[2] > 200) { invalidInput("weight"); return; }
    
    console.log(`Age: ${arguments[0]}, Height: ${arguments[1]}, Weight: ${arguments[2]}`);
}

function invalidInput(type) {
    console.log(`The input for "${type}" was found to be invalid.`);
    return;
}
<!DOCTYPE html>
<html>
<body>

<form id="submit">
  <label for="userinfo">Information:</label>
  <input type="text" id="userinfo" placeholder="Age-Weight-Height" pattern="[0-9]{2}-[0-9]{3}-[0-9]{2,3}" title="Three sets of three-digit numbers separated by hyphens e.g. 123-123-123"><br><br>
  <input type="submit">
</form>

</body>

</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Saving multiline text input values separately in a MySQL 5 database

Here is the input field I am using: InputArea I would like to store each input value separately. const [textInput, setTextInput] = useState('') <TextInput multiline={true} style={allStyles.textInput} placehold ...

Struggles encountered when trying to fetch text using a custom xpath or css selector in firebug

Struggling to extract a specific text snippet from a webpage using Selenium. The code I'm dealing with on the page is as follows: <div id="BVRRRatingOverall_Review_Display" class="BVRRRating BVRRRatingNormal BVRRRatingOverall"> <div class="B ...

Unable to remove the vertical dropdown menu padding issue in Firefox

issue: https://i.stack.imgur.com/qisVn.jpg My website appears correctly on IE, Opera, and Chrome, but in Firefox, there is a spacing problem between each image in the dropdown menu. I suspect the issue lies within the CSS code. The same spacing issue occ ...

How can I create a box-shaped outline using Three.js?

As someone new to threejs, I have been trying to figure out how to render a transparent box around a symbol in my canvas. The box should only display a border and the width of this border should be customizable. Currently, I am using wireframe to create a ...

Displaying an HTML button above JavaScript code

Hello, I am currently working on a project that involves displaying the Earth and I am in need of assistance with positioning some buttons on the screen. Currently, I am facing an issue where the buttons appear either above or below the JavaScript code. I ...

What is the best method to store the name of an image as a session variable?

<!--images acting as buttons--> <form> <img src="peanuts.jpg"" class="qac left" onclick="qac_search()" name="Peanuts"> <img src="milk.jpg" class="qac" onclick=&qu ...

What is the best way to display just a single view?

Currently, while using Node.JS and Express web framework, I am facing an issue with the res.render() function. Below is the code snippet in question: exports.init = function(){ return function(req, res, next) { /* FORM CONTACT */ ...

I am looking to dynamically alter the CSS background URL using JavaScript

Currently, I am looking to update the background image url using JavaScript. Most tutorials I've come across involve having the image downloaded on the desktop and then providing its path. However, in my scenario, the user will input an image link whi ...

How to set the default value of a select dropdown in PHP

I came across this snippet of code: <td> <select class="versionSelect"> <option value="5" <?php if($item->version === "5") echo "selected='selected'"; ?>>5</option> <option value="6" <?php ...

I'm having trouble rendering the div using PHP code within an AJAX request in CodeIgniter

I am a beginner in AJAX and I'm attempting to display specific restaurant data based on the selected area from a dropdown using AJAX. However, I am facing issues with displaying the restaurant view correctly. Can someone please guide me on how to proc ...

What steps can I take to fix validation errors in my Node.js application?

I am working on a validation that restricts creating more than 5 players for a specific idteam. My tech stack includes node.js with express, mLab (MongoDB) and Heroku. playerModel.count({ idteam: player.idteam }, function (err, count) { console.lo ...

Replace the function if it is specified in the object, otherwise use the default functionality

Having a calendar widget written in TypeScript, I am able to bind a listener to a separate function. However, I desire this separate function to have default functionality until someone overrides it in the config object passed to the constructor. Within th ...

Discord.js counter feature

Recently, I attempted to create my own counting system for my server inspired by bots like countr. Here is the code snippet I came up with: if (message.channel.id === "794733520458612736") { const numdb = db.get("numdb"); if (me ...

Can a post request be sent in Node/Express using just HTML and server-side JavaScript (Node.js)?

Can a post request be made in Node/Express using only HTML and Server-side Javascript? (HTML) <form action="/submit-test" method="post"> <input type="text" name="id"> <button type="submit">Submit</button> </form> (N ...

I am struggling to save the value from my input field into the app.component.ts file

Having some trouble storing an input from my form into a property. After submitting, the console.log is showing undefined in the console. I've experimented with different variations, but none seem to be working as intended. <form> <input #i ...

Adjust the size of the Div and its content to fit the dimensions of

Currently, I have a div containing elements that are aligned perfectly. However, I need to scale this div to fit the viewport size. Using CSS scale is not an option as it does not support pixel values. https://i.stack.imgur.com/uThqx.png I am looking to ...

Tips for structuring a JSON array of objects with the help of jQuery and Bootstrap

Currently, I am in the process of developing an online shopping application using Struts 2, MySQL, jQuery, JSP, Bootstrap, Gson, and Tomcat. In my Java entity, I have a class named Product, which is linked to a controller action that returns a JSON array ...

Learn the process of dynamically loading scripts and their functions in Angular

At first, I had the following code statically placed in Index.html and it was functional. <script src="/le.min.js"></script> <script> LE.init({ token: 'token', region: 'x' }); </script> ...

Responses that include a 204 error code followed by a 500 error code

I have a scenario where my application needs to send data to an API developed by our team leader using NodeJS with Express.js. On my side, I have a Laravel application that utilizes VueJS for the UI. Inside the Vue JS component, I am making use of axios t ...

Execute a PHP script to modify a section of a PHP file

I successfully implemented a piece of code into a PHP file by manually searching for the right section and inserting it. Now, I am looking to automate this process with an install script for my code. The ideal installation script would: 1. Copy the exist ...