Home > Blockchain >  How to create input text patterns (html forms)
How to create input text patterns (html forms)

Time:04-13

I have tried to create an input text pattern that only allows 8 digits and a capital or simple "d" at the end of it but I can't seem to limit the number of digits. example 12345678d or 12345678D

<input type="text" name="studentid" placeholder="Student ID"
                       pattern="[0-9] [dD]" >

CodePudding user response:

The answer is very simple but I'm gonna explain why it's important to think and handle edge cases. If you aren't interested in that, go to the end of the code block and copy the regex pattern.

Let's start with the pattern you have tried:

var pattern = /\d [dD]/
var txt1 = "123458D";

console.log(txt1.match(pattern)); 
That's a false positive, it should not have matched. the problem is that we have not specified that we need 8 digits, so let's fix that.
var pattern = /\d{8}[dD]{1}/
var txt1 = "123458D";

console.log(txt1.match(pattern)); //Doesn't match, so Good now

//But, We are not done yet
var txt2 = "123456789D"
console.log(txt2.match(pattern)); //["23456789D"] Might be a problem

We have run into another problem, let's fix that by making sure that we get only 8 digits starting from the beginning.

var pattern = /^\d{8}[dD]{1}/
var txt3 = "123456789D"
console.log(txt3.match(pattern)); //Doesn't match, so Good now

var txt4 = "12345678Dblah blah 2312412"
console.log(txt4.match(pattern)); //["12345678D"] Might be a problem

Arrgghh! We are still not done. Let's put that last one fix and make sure that we end with a "D" or "d".

var txt4 = "12345678Dblah blah 2312412"
var pattern = /^\d{8}[dD]{1}$/
console.log(txt4.match(pattern)); //Doesn't match now, We are good

CodePudding user response:

You can specify that there should be exactly 8 digits with pattern="[0-9]{8}[dD]".

CodePudding user response:

The maxlength attribute is used to set a limit of maximum character one can enter in the textbox.

<input type="text" maxlength="9" pattern ="[0-9]{8}[dD]">

  • Related