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?
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?
Share Improve this question edited May 30, 2017 at 7:36 Tushar 87.2k21 gold badges163 silver badges181 bronze badges asked May 30, 2017 at 7:35 ishan shahishan shah 6032 gold badges10 silver badges28 bronze badges 6 | Show 1 more comment3 Answers
Reset to default 14I 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);
}
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");
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)
});
[a-zA-Z0-9_]
this in your html .i think its apattern attr
– prasanth Commented May 30, 2017 at 7:36elem.getAttribute("[a-zA-Z0-9_]")
will return??? – Tushar Commented May 30, 2017 at 7:37elem.getAttribute("attributeName")
would return your pattern. – Eytibi Commented May 30, 2017 at 7:42