Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern validation with JavaScript

I want a pattern with letters and numbers only.

This is how I do it...

JavaScript file:

var pattern_checked = checkPattern(); 

function checkPattern(){
        var elem = document.getElementById("name");

        var pattern = elem.getAttribute("[a-zA-Z0-9_]");
        var re = new RegExp(pattern);
        if (re.test(elem.value)) {
            return true;
        } else {
            return false;
        }
    }

But in both the cases, I'm getting false.

What is wrong in this code?

like image 962
ishan shah Avatar asked Dec 10 '22 11:12

ishan shah


2 Answers

I believe you meant to do:

function checkPattern() {
    var elem = document.getElementById("name");

    // Allow A-Z, a-z, 0-9 and underscore. Min 1 char.
    var re = /^[a-zA-Z0-9_]+$/;

    return re.test(elem.value);
}
like image 61
Alvin Teh Avatar answered Dec 28 '22 15:12

Alvin Teh


Example fiddle

Your problem should be at this line.

var pattern = elem.getAttribute("[a-zA-Z0-9_]");

Attribute should usually have a name with value. But from your example, it seems like the value is also name. The HTML code should be something like below:-

<input type='text' id='name' pattern='[a-zA-Z0-9_]'>

Then to get the pattern

var pattern = elem.getAttribute("pattern");
like image 32
Jiro90 Avatar answered Dec 28 '22 15:12

Jiro90