0

I'm trying to create a form, and set the pattern and title fields programatically through JS. Can someone help me with working out why this isn't working. The code below results in not being able to enter anything into the form field and the popup error saying "match the requested format".

var node = document.getElementById("text");
node.setAttribute("pattern", "\d+");
node.setAttribute("title", "Six or more characters");
<p>A form with a password field that must contain a positive integer:</p>
<form action="/action_page.php">
  Enter a number: <input type="text" id="text" name="text">
  <input type="submit">
</form>
j08691
  • 204,283
  • 31
  • 260
  • 272
croc_hunter
  • 285
  • 3
  • 12
  • 3
    You need to escape your backslash. If you inspect the resulting HTML in the web console, you can see that your `pattern` attribute ends up being `"d+"` – Hamms Sep 28 '17 at 20:19
  • OK thanks that fixes the validation so now i can enter the number and it will validate, but if i try entering something like "sgdf" i still see a popup error saying "match the requested format" and not "Six or more characters". – croc_hunter Sep 28 '17 at 20:28
  • Possible duplicate of [How can I create a custom message when an HTML5 required input pattern does not pass?](https://stackoverflow.com/questions/19122886/how-can-i-create-a-custom-message-when-an-html5-required-input-pattern-does-not) – CBroe Sep 28 '17 at 20:56

1 Answers1

1

The \ is an escape character. If you want to write a \ you will have to escape it with \\

var node = document.getElementById("text");
node.setAttribute("pattern", "\\d+");
node.setAttribute("title", "Six or more characters");
node.setAttribute("oninvalid", "setCustomValidity('Six or more characters')");
// this line is needed to clear the error status onchange, so user can enter newly correct input
node.setAttribute("onchange", "try{setCustomValidity('')}catch(e){}");
<p>A form with a password field that must contain a positive integer:</p>
<form action="/action_page.php">
  Enter a number: <input type="text" id="text" name="text">
  <input type="submit">
</form>
AVAVT
  • 7,058
  • 2
  • 21
  • 44
  • Thanks, yes that is what Hamms said above. Also your example doesn't work as you have an extra \\ after the d+ which breaks it. – croc_hunter Sep 28 '17 at 20:51
  • Also if i type in some alpha characters, I still see a popup error saying "match the requested format" and not "Six or more characters". Do you know why the title attribute isn't working? – croc_hunter Sep 28 '17 at 20:52
  • You're right, thanks it was an typo. About the error message, please check my edited answer. – AVAVT Sep 28 '17 at 21:22