Pattern validation with JavaScript
Asked Answered
B

3

6

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?

Barty answered 30/5, 2017 at 7:35 Comment(6)
Can you post your html also .Are you sure you have attribute like [a-zA-Z0-9_] this in your html .i think its a pattern attrIlbert
Did you check what elem.getAttribute("[a-zA-Z0-9_]") will return???Cyte
I guess your pattern is the attributes value. elem.getAttribute("attributeName") would return your pattern.Tasteless
@prasad I think I'm doing something wrong. How do I use that pattern?Barty
yes you are doing wrong .That why i was asking the html code @ishanshahIlbert
@prasad I was using the method wrongly. Thanks for your efforts!Barty
S
14

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);
}
Sacramentarian answered 30/5, 2017 at 7:40 Comment(2)
re.test() will return boolean value. Just return it.Algebraic
That is exactly what I was looking for. Thank you so much!Barty
P
1

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");
Pigling answered 30/5, 2017 at 7:51 Comment(1)
Yeah got it! I didn't mention pattern in html file.Barty
L
1

With pure jquery/js it is possible:

<input type="text" placeholder="Ex 15.04.2023" class="date" required pattern="\d\d\.\d\d\.\d{4}"/>


css:
.date:invalid{
    background:red !important;
}

script:
$('.date').keyup(function(){
  console.log($('.date:valid').length)
});
Lynd answered 5/7, 2023 at 11:4 Comment(1)
For some reason, an empty input will validate my regex, so I should also check to make sure that my input.value is not equal to "".Aleshia

© 2022 - 2025 — McMap. All rights reserved.