Linked Questions

Popular Questions

I'm working on a form where the user first selects "USA" or "International" on a radio button. Depending on the country of choice, the telephone input field should require either a 10 digit US number or else an international phone number with a different pattern.

I'm using native HTML validation with the required attribute and a regex pattern. At the moment I have placeholder, pattern, and title attributes for a US 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>

How could I implement the placeholder, pattern, and title for the international number?

I could have two divs in the HTML for each and display them with JS depending on the radio button selection. Or I could leave the HTML as it is and insert the HTML or the values of the attributes for the international selection with JS if it is selected. But I'm wondering if there is a better way that will work or at least be acceptable if JS is disabled or not available.

Related Questions