0

I have this reg ex for alphanumeric validation that I got from this post but it is not working with this function (I have a similar function for email and it works)

 function checkName(field) {

        var x = document.getElementById(field).value;
        var y = /^[a-z0-9]+$/i;
        //var z = /^[0-9]*$/;

        if (x == "" || !x.match(y) ) {
            alert("Invalid character");

            if (x.length <= 2 || x.length >= 15) {
                alert("Insert a name between 3 and 15 characters");
            }

            return false;
        }

    }

If I write some string/name I get both alerts. Can someone tell me what is wrong with this function?

Community
  • 1
  • 1
glassraven
  • 323
  • 2
  • 13

2 Answers2

2

Below is the approach for alphanumeric validation:

 function checkName(field)
 {
       var x = document.getElementById(field).value;
       if (x.length <= 2 || x.length >= 15)
       {
           alert("Insert a name between 3 and 15 characters");
           return false;
       }
        var y = /^[0-9a-zA-Z]+$/;
        if (x == "" || !x.match(y) )
        {
           alert("Invalid character");
           return false;
        }
        
        alert("ALL OK");
        return true;
 }
<input type="text" id="textName" />
<button onClick="checkName('textName');">Check</button>

The Regex check for capital and small alphabets and numbers, and also checks for the length.

Shakti Phartiyal
  • 6,156
  • 3
  • 25
  • 46
1

Your code works for me

 function checkName(field) {
        console.log(field);
        var x = field;
        var y = /^[a-z0-9]+$/i;
        if (x == "" || !x.match(y) ) {
            console.log("Invalid character");
        }
        if (x.length <= 2 || x.length >= 15) {
            console.log("Insert a name between 3 and 15 characters");
        }
    }
//valid
checkName('testdskfjskdlf');
//invalid
checkName('slkjf*%');
//too long
checkName('jjjjjjjjjjjjjjjjjjjjjjjjjjj');
Mokkun
  • 708
  • 4
  • 14