Home > Enterprise >  How to add an onkeyup with a Regular Expression to a text input in HTML?
How to add an onkeyup with a Regular Expression to a text input in HTML?

Time:04-28

I need help creating a RegEX(Regular Expression) to insert in my HTML input's onkeyup attribute.

L#######L

  1. The first character only accepts N, followed by 7 numbers (0-9), then the last character would only accept R.
  2. The first character only accepts English alphabets (A-Z), followed by 7 numbers (0-9), then the last character would only accept English alphabets (A-Z).

Thank you so much in advance!

CodePudding user response:

You can try this

function firstRegEx(val)
{
  val.match(/^N[\d]{7}R$/)? firstInput.className="valid": firstInput.className="invalid"
}

function secondRegEx(val)
{
  val.match(/^[A-Z]{1}[\d]{7}[A-Z]{1}$/)? secondInput.className="valid": secondInput.className="invalid"
}
input{
outline: none;
}
.valid{
border: 1px solid green;
}

.invalid{
border: 1px solid red;
}
<input id="firstInput" type="text" onkeyup="firstRegEx(event.target.value)">

<input id="secondInput" type="text" onkeyup="secondRegEx(event.target.value)">

CodePudding user response:

Regex For The Two Cases are:

  1. N\d{7}R
  2. [A-Z]\d{7}[A-Z]

to check you can use .match() function. like "N0123456R".match(/N\d{7}R/) it returns null if match is not found.

  • Related