0

I need to replace a code example: OD3 - The first must always be alpha character, 2nd alphanumeric and the last must always be numeric. What's the regular expression to check and replace the first and regulate the rest to enter correctly? A user could enter in the number 0 instead of the letter O, so I want to correct it immediately...

this is what I have so far: onkeyup="this.value=this.value.replace(/[^a-zA-z]/g,'')

2
  • 3
    What do you mean by - regulate the rest to enter correctly? Commented Aug 2, 2013 at 11:35
  • What should happen if it's not correct? Blank out the value? Also how many replacements are there, is it just 0=O ? Commented Aug 2, 2013 at 11:43

2 Answers 2

1

First, I'd suggest just indicating the error to a user instead of replacing the values. Something like

oninput="if (! /^[a-z][a-z0-9]\d$/i.test(this.value) ) displayMessage('incorrect code');"

If you definitely have to replace the value on the fly, you could do somthing like that:

oninput='validateValue()';
...
function validateValue() {
    var val = this.value;
    if (! /[a-z]/i.test(val[0]) this.value = '';
    else if (! /[a-z0-9]/i.test(val[1]) this.value = val.slice(0,1);
    else if (! /\d/.test(val[2]) this.value = val.slice(0,2);
}
Sign up to request clarification or add additional context in comments.

Comments

0

Better have like this.

onkeyup="testRegex(this.value)";

It is not .replace() it is .test()

function testRegex(value) {
   if(value.test(/[^a-zA-z]/g)) {
       alert("Please enter correct value");
       return false;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.