简体   繁体   中英

Javascript Replace - Regular Expression

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,'')

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);
}

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM