What is the best way to implement form fields that have varying validation patterns based on different conditions?

Currently, my focus is on developing a form that prompts the user to choose between "USA" or "International" via radio buttons. The input field for telephone numbers should then adapt its requirements based on the selected country - either a 10-digit US number or an international phone number with a distinct format.

To enforce validation, I am leveraging native HTML attributes such as required along with a regex pattern. Presently, I have integrated placeholder, pattern, and title attributes tailored for a US phone number.

<form>

  <div>
    <fieldset>
      <legend>Country</legend>
      <p>
        <input type="radio" name="country" id="usa" value="usa" required />
        <label for="usa">USA</label>
      </p>
      <p>
        <input type="radio" name="country" id="int" value="int" required />
        <label for="int">International</label>
      </p>
    </fieldset>
  </div>

  <div>
    <label for="telephone">Telephone</label>
    <input
      type="tel"
      name="tel"
      id="tel"
      placeholder="123 456 7890"
      required
      pattern="(?:\d{1}\s)?\(?(\d{3})\)?-?\s?(\d{3})-?\s?(\d{4})"
      title="A valid US 10 digit phone number is required."
    />
  </div>

  <button id="submit" type="submit">Submit</button>

</form>

My query pertains to the implementation of placeholder, pattern, and title for international numbers.

One approach could involve creating separate div elements in the HTML for each scenario and toggling their visibility using JavaScript upon radio button selection. Alternatively, I can retain the current HTML structure and use JavaScript to dynamically insert the relevant HTML or attribute values specific to international selections. However, I am exploring more efficient methods that are inclusive of scenarios where JavaScript may be disabled or unavailable.

Answer №1

When following this path, it is recommended to add a click-handler to your radio buttons. This will allow you to adjust the attributes of your input field accordingly.

<form>
  <div>
    <fieldset>
      <legend>Country</legend>
      <p>
        <input type="radio" name="country" id="usa" value="usa" required />
        <label for="usa">USA</label>
      </p>
      <p>
        <input type="radio" name="country" id="int" value="int" required />
        <label for="int">International</label>
      </p>
    </fieldset>
  </div>

  <div>
    <label for="telephone">Telephone</label>
    <input type="tel" name="tel" id="tel" disabled/>
  </div>
  <button id="submit" type="submit" disabled>Submit</button>
  <script>
  const phoneInput = document.querySelector('#tel');
  const submitButton = document.querySelector('#submit');

[...document.querySelectorAll('input[name="country"]')].forEach(radio => {
radio.addEventListener('click', function(){
  phoneInput.disabled = false;
    submitButton.disabled = false;
    if(this.value == 'usa') {
    phoneInput.setAttribute('placeholder', '123 456 7890');
      phoneInput.setAttribute('pattern', 'xyz');
      phoneInput.setAttribute('title', 'A valid US 10 digit phone number is required.');
    }
    else if(this.value == 'int'){
      phoneInput.setAttribute('placeholder', '+1234567890');
      phoneInput.setAttribute('pattern', 'abc');
      phoneInput.setAttribute('title', 'International phone number format is required.');
    }
  });
});
  </script>
</form>

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

Set the styling of a div element in the Angular template when the application is first initialized

I have a question about this specific div element: <div class="relative rounded overflow-clip border w-full" [style.aspect-ratio]="media.value.ratio"> <img fill priority [ngSrc]="media.value.src || ftaLogo" ...

Adjust the size of the embedded iframe to match the dimensions of the containing div

Is there a method to resize the iframe embed code for a vine so that it fits within the boundaries of the enclosing div? The supplied embed code already includes sizing information as shown below: <iframe src="https://vine.co/v/iMJzrThFhDL/embed/simp ...

Retrieve all tags that come after a specific <a> tag inside a <td> element using Scrapy

Looking to extract information from this specific webpage using Scrapy: My goal is to retrieve the summaries from the GeneCard, which are structured in HTML as follows: <td> <a name="summaries"></a> <br > <b>Entr ...

"Extending Material-UI: Utilizing Multiple Snackbar Components

I've been struggling to display multiple warnings using Snackbar from the Material UI library in my React project. I haven't found any examples with React, only Vue. Can anyone help me with this? Here is the code that I have tried so far: https: ...

How to use jQuery to disable td and ul elements

Has anyone successfully disabled a "td" or "ul" element using jQuery, similar to how we disable textboxes and other input types? I attempted to use the "prop" and "attr" functions in jQuery, but they did not seem to work. Is there a way to achieve this? ...

Data table created with functional components is not refreshing when columns are added or removed, which are stored in the state as an array of objects

I’ve been working on setting up a datatable with a checkbox dropdown feature to add or remove columns from the table. Everything is functioning properly, except for one issue – the table is not refreshing unless I click on one of the header titles. At ...

Responsive Div that Resizes Proportionally within Parent Container

Having a div element that adjusts its height based on width to maintain aspect ratio, I aim to place this div within another while maximizing available space vertically and horizontally without any cropping. It seems that object-fit: contain, typically use ...

The value of Vue.js props appears as undefined

It appears that I may be misunderstanding how props work, as I am encountering difficulty passing a prop to a component and retrieving its value, since it always shows up as undefined. Route: { path: '/account/:username', name: 'accco ...

Enhancing user interfaces with jQuery by updating DOM elements

Can anyone help me figure out how to update a webpage so it functions as a report that multiple people can contribute to? I'm using forms to collect data and want it to instantly display under the correct category headings. Currently, I'm using j ...

Proper technique for handling asynchronous results in a Vue component

Where is the ideal place to wait for a promise result in the Vue component lifecycle? Here's a runnable example: https://codesandbox.io/s/focused-surf-migyw. I generate a Promise in the created() hook and await the result in the async mounted() hook. ...

Form submission is not functioning as expected

I am having trouble with my form submission. When I try to submit the form, nothing happens. I have tried various solutions but have not been able to resolve the issue. I have reviewed all available resources but still cannot figure out why my code is not ...

Creating dynamic and engaging videos using Angular with the ability to make multiple requests

I am facing an issue while working with videos in Angular. I am fetching the video URLs from an API to embed them in my application using the sanitazer.bypassSecurityTrustResourceUrl function provided by Angular. The videos are being displayed correctly wi ...

What is the best way to direct users to an input field within a dynatree title?

I am currently utilizing Dynatree to display a tree view, and my goal is to focus on an input field within the dynatree title element. However, I am encountering an issue where the focus is being lost. My code attempts to address this problem but unfortun ...

AngularJS ng-repeat: displaying a list of filtered outcomes exclusively

I currently have a ng repeat that loops through a set of results. <a class="list-group-item" href="#trip/{{trip.id}}/overview" ng-repeat="trip in trips | filter:search | limitTo:-15"> Basically, as I enter more text into my input field, the list sh ...

struggling with beginner-level JavaScript issues

Hey there, I've been running into a bit of an issue with my basic javascript skills: function tank(){ this.width = 50; this.length = 70; } function Person(job) { this.job = job; this.married = true; } var tank1 = tank(); console.log( ...

Exploring the Power of 2D Arrays in JavaScript

Hey there! I'm having trouble defining a 2D array in JS. Two errors are getting in my way and I can't figure out what's going wrong. i is generated by a for loop - it's defined. Even when I try replacing i with 0, the same error occurs. ...

Extracting and retrieving data using JavaScript from a URL

After reviewing some code, I am interested in implementing a similar structure. The original code snippet looks like this: htmlItems += '<li><a href="show-feed.html?url=' + items[i].url + '">' + items[i].name + '& ...

Maximizing Angular and Require's Potential with r.js

I'm facing some challenges while setting up r.js with require in my Angular application. As I am new to AMD, solving this issue might be a simple task for someone experienced. However, I need to maintain the current directory structure as it allows me ...

The self-made <Tab/> element is not functioning properly with the ".Mui-selected" class

I have customized a <Tab/> element and I want to change its selected color using Sandbox demo code export const Tab = styled(MuiTab)({ "&.Mui-selected": { color: "red" } }); However, I've noticed that: 1. Apply ...

Is there a way to sort search outcomes by a drop-down menu in Next.js?

I am currently working on implementing a filter for my data based on selections made in a drop-down menu. Here's the setup: I have MSSQL data being pulled into NextJS using Prisma (ORM). My goal is to create a dropdown filter that will refine the di ...