1

I am creating a form that will allow a user to enter a birthday with month, day and year. For year, I am trying to write the html code such that it will only allow positive number and also limit it to 4 digits. Here is the code in question:

<input type="number" name="year" maxlength="4"  max="9999" min="0" step="1" placeholder="YYYY" p="[0-9]{4}" style="color:#888;" required/> 

I've scoured the web for a solution to what I am trying to do but every time I try it, it will allow me to enter a number that is greater than 4 digits... basically I am trying to limit the user to enter a valid birth year:

Any advice?? thanks in advance!!

Birth year greater than 4 digits input

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
Brian Lee
  • 87
  • 1
  • 1
  • 10
  • Oh, and for this project I have been advised that I shouldnt use type as "text", for that could cause issues with my program down the road. – Brian Lee Apr 08 '17 at 21:03
  • 1
    `p="[0-9]{4}"` should be `pattern="[0-9]{4}"` (or atleast I've never encounter `p` attribute) That also requires the browser is HTML5 compatible.. You had PHP tag, is there PHP? You also could use JS. – chris85 Apr 08 '17 at 21:05
  • nope, unfortunately that doesn't change a thing :( – Brian Lee Apr 08 '17 at 21:06
  • maxlength doesn't work with numbers (at least in chrome). without type="number" it works as expected. Doesn't really help, I know. – Jeff Apr 08 '17 at 21:06
  • 2
    You've asked six questions and never accepted an answer. People are going to get tired of helping you if you keep that behaviour up. – miken32 Apr 08 '17 at 21:07
  • 1
    Possible duplicate of [How to set maximum length in input type=number?](http://stackoverflow.com/questions/37538357/how-to-set-maximum-length-in-input-type-number) – kennytm Apr 08 '17 at 21:13
  • Does this answer your question? [How can I limit possible inputs in a HTML5 "number" element?](https://stackoverflow.com/questions/8354975/how-can-i-limit-possible-inputs-in-a-html5-number-element) – Laura Jan 08 '20 at 15:00

2 Answers2

2

thank you kennytm, your link has answered by question. I just needed to add this

onKeyPress="if(this.value.length==10) return false;
Brian Lee
  • 87
  • 1
  • 1
  • 10
2

Two changes are required:

  1. Change input type=number to type=text. This will start accepting text input without constraints.
  2. BUT your regular expression pattern will bound text input to numbers only.
  3. Also edit p=[0-9]{4} to pattern="[0-9]{4}".

<input type="text" name="year" maxlength="4"  min="0" max="9999" step="1" placeholder="YYYY" pattern="[0-9]{4}" style="color:#888;" required/>
Hamza Rashid
  • 1,329
  • 15
  • 22