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

The WebSocket handshake for the cross-domain connection encountered a failure with an unexpected response code of 400

I'm facing an issue with implementing socket.io in a Node.js application. The setup involves the application residing on a subdomain, while the front-end is hosted on the www version of the domain. Unfortunately, hosting the front-end and Node.js ser ...

Can the concept of partial class be used in an AngularJS controller?

Is it possible to organize code into groups using partials in angularjs? The issue is that my controller has become too cluttered with a lot of code for different methods and functionalities, making it difficult to read. I want to maintain the same contro ...

npm error: The package name "__init__.py" is invalid because it cannot begin with an underscore character

Having trouble running a cucumber/gherkin script from Jenkins with Node.js? When attempting to execute the gherkin script, I encountered an error message: npm ERR! Invalid package name "init.py": name cannot start with an underscore package.json { &q ...

A guide on combining $count and $project in Node.js Mongoose aggregate functions

Looking to retrieve filtered data along with the total count in a single query? Here is the code snippet I am using: var SubId = 1; var TypeId = 1; var lookup = { $lookup: { from: 'sub_types', localField: 'sub_ ...

Retrieve the number of rows in the table component

I'm in need of getting the row count from a table component that I have built using vuejs. My goal is to display the row count outside of the table component structure. The issue with the code snippet below is that it doesn't show the correct row ...

What are the steps for rearranging a table column?

I am trying to show a text file in a table and allocate some code to each entry. I can display the text file. I can assign the code for each record (though this part is still under development). However, I have encountered an issue. The columns of the t ...

Creating a template based on an object type in JavaScript with Angular: A step-by-step guide

I have a collection of objects, each with a property indicating its type. Here's an example: [ { "type" : "date", ... },{ "type" : "phone", ... },{ "type" : "boolean", ... } ] I'm ...

Implementing automatic pagination based on container height using jQuery

Looking to convert an AngularJS fiddle into jQuery. The goal is to create pagination using several p tags only with jQuery. Current code: <div class="parent"> <p>text1</p> <p>text2</p> <p>text3</p> ...

Encountering an issue in a Vue console where the $ref is returning null and prompting an error message

It's puzzling why I keep encountering a console error in Vue that says "cannot read null of a $ref". Despite having the correct HTML template and adding logic to the script tag as needed, I'm still facing this issue - Cannot read properties of nu ...

Guide to configuring capybara-webkit for testing ajax requests and capturing screenshots containing HTML with loaded CSS and JavaScript

Having some trouble setting up capybara-webkit on my Rails 4.2.1 app. Tests are running fine, links are being clicked, and ajax calls are working, but there's one odd issue with capybara-screenshot gem. I wanted to capture html screenshots with all as ...

Adjusting the size of a React element containing an SVG (d3)

In my simple react app, I have the following component structure: <div id='app'> <Navbar /> <Graph /> <Footer /> </div> The Navbar has a fixed height of 80px. The Footer has a fixed height of 40px. The Graph i ...

Trigger Element Upon Click

Forgive me in advance for the lack of quality in this question, but I'll proceed anyway: All I want is for an element to slide open when clicked with a mouse! That's all! More specifically, I am looking for a single menu item that, upon clickin ...

Incorporating D3.js into Angular 6 for interactive click events

Currently working on building a visual representation of a tree/hierarchy data structure using d3.js v4 within an Angular environment. I've taken inspiration from this particular implementation https://bl.ocks.org/d3noob/43a860bc0024792f8803bba8ca0d5e ...

Despite declaring a default export, the code does not include one

Software decays over time. After making a small modification to a GitHub project that was three years old, the rebuild failed due to automatic security patches. I managed to fix everything except for an issue with a default import. The specific error mess ...

Print the message in the Google Cloud Logging console when a request is made

Using NodeJS with Express in my application deployed to Google Cloud Run, I have encountered an issue with the logs. The request log from Google and the console.logs I intentionally emit can become mixed up when handling a large number of requests. I disc ...

The MEAN application experienced a sudden crash following a series of queries

Here is my mongoose configuration: mongoose.Promise = global.Promise; mongoose.connect(config.dbhost + config.dbname, function(err){ if(err){ console.log(err); } else { console.log('Connected to the database successfully.'); ...

A guide to validating a v-edit-dialog within a v-datatable

As I navigate my way through vue.js and vuetify, I am faced with an issue regarding the validation of input within a v-edit-dialog located inside a v-datatable. Despite having functional validation in place, the save button remains enabled and accepts inva ...

Can you please explain the distinction between the statements var a = b = 2 and var a = 2; var b = 2;

Whenever I try to declare a variable within a function, I encounter an issue. var b = 44; function test(){ var a = b = 2; } However, the following code works without any problems: var b = 44; function test(){ var a; var b = 2; } The global ...

Issue in VS Code installation - eslint

When attempting to install eslint using the command "npm i eslint," I encountered the error message "`-- [email protected] extraneous" As a newcomer to npm and VS Code, I have successfully installed various extensions without any issues. However, in ...

`Controlling and Organizing node.js Middleware`

When developing middleware that works in conjunction, what is the best practice for organizing and managing their functionality? Currently in my server.js file, I have them simply listed one after another with app.use calls. I've realized that if th ...