scofildo
scofildo

Reputation: 33

javascript regular expression to test letter and number existens

i have this regular expression in this code:

function validateUser() {
   var e = /^[a-zA-Z](?=.*[0-9]).*$/;
    else(e.test(document.getElementById("username")) == false){
        document.getElementById("s").innerHTML=("error");   
    }
    else{
        document.getElementById("s").innerHTML=("ok");
    }

i want it to test if the string starts with a letter and contains at least 1 number but even if i enter a string that contains a number i still get the error msg!

Upvotes: 1

Views: 55

Answers (4)

Mamun
Mamun

Reputation: 68933

Try the following:

function validateUser(thatObj) {
 var patt = /^[a-zA-Z](?=.*[0-9]).*$/;
   if(patt.test(thatObj.value) == false){
        document.getElementById("s").innerHTML=("error");   
   }
   else{
        document.getElementById("s").innerHTML=("ok");
   }
 }
User Name: <input type="text" id="username" oninput="validateUser(this)"/><br>
Status: <span id="s"></span>

Upvotes: 0

user557597
user557597

Reputation:

You're missing a scope closure syntax and a conditional is corrupt.
Telltale missing closure is the error is generated on line 20 or there abouts.

It should be

function validateUser() {  // <- Begin function block
   var e = /^[a-zA-Z](?=.*[0-9]).*$/;
    // else <- if what ? 
    if(e.test(document.getElementById("username")) == false){
        document.getElementById("s").innerHTML=("error");   
    }
    else{
        document.getElementById("s").innerHTML=("ok");
    }
} // <- function block closure

Upvotes: 0

alaric
alaric

Reputation: 987

The following will test the full string based on your stated criteria:

/^[a-zA-Z]+[0-9]+/

Explanation:

^ match start of string

[a-zA-Z]+ match one or more of any letter of the alphabet

[0-9]+ match one or more of any numerical digit

Upvotes: 0

TemporalWolf
TemporalWolf

Reputation: 7952

/^[a-zA-Z].*\d.*$/

Will allow any string which starts with a letter and contains at least 1 digit.

See it on regex101

Upvotes: 1

Related Questions