javascriptregextypescriptformsinput

Can the pattern attribute of a form input be set dynamically to match the entered value of another input in that form?


The question basically says it all, but to give a little more context, I have a form with one of those standard approaches for email: an Email input and a Confirm Email input that must of course match each other in order to be valid.

I was wondering if I can dynamically set the pattern on the Confirm Email input to be a regex of whatever value the user enters into the first Email input field on keyup or focusout or something similar. Does that make sense and would something like this even be do-able/possible?

I know how to write the event listener for keyup/focusout, I'm just not sure how to write a regex for this situation and/or if it would even work to dynamically create the pattern attribute like this?

Oh, also, no jquery please. I'm working in vanilla javascript. ES6, typescript, etc. are fine, but jquery solutions won't work for this project.

Thanks in advance!


Solution

  • A regex can just be a regular string, so pretty simple. Luckily if you don't allow illegal characters in the email, you won't need to escape any characters for the regex. If you allowed something like [ in the email you would need to escape it like \[

    const i1 = document.getElementById('1');
    const i2 = document.getElementById('2');
    
    i1.addEventListener('change', (ev) => {
      i2.setAttribute('pattern', ev.target.value);
    });
    <form>
      <input id="1" required pattern="[\w\-\+\.]+@[\w\-\+\.]+" title="Email ex. a@b" />
      <br />
      <br />
      <input id="2" required pattern="" title="Match email above"/>
      <br />
      <br />
      <input type="submit" />
    </form>

    The email regex I have there is good enough, it just checks for an @ symbol and that there are no illegal characters. If you were really validating an email you would just send a confirmation with a link.

    You can check this thread for the absurdity of validating emails with a regex: How can I validate an email address using a regular expression?