I having a issue trying to check if a textbox only contains a-z 0-9 values using JavaScript.
I have a textbox on my page:
<input type="text" id="first_name" class="first_name" value="">
I am using the following JavaScript Function to check my textbox:
// Function to check letters and numbers
function alphanumeric(inputtxt)
{
//alert(inputtxt);
var letters = "/^[0-9a-zA-Z]+$/";
if(inputtxt.value.match(letters))
{
alert('accepted');
}
else
{
alert('Please input alphanumeric characters only');
return false;
}
}
And I am calling my function like this:
var test = alphanumeric(document.getElementById("first_name").value);
However nothing is happening.
If I alert 'inputtxt' in my alphanumeric function it returns my value I have in my textbox so I know there is a value to be checked, but it doesn't seem to go on from there.
Does anyone know where I have gone wrong?
I am trying to do this with JavaScript (no jQuery).
To check if a string contains special characters, call the test() method on a regular expression that matches any special character. The test method will return true if the string contains at least 1 special character and false otherwise.
click(function(){ var fn = $("#folderName"). val(); var regex = /^[0-9a-zA-Z\_]+$/ alert(regex. test(fn)); }); }); This return false for special chars and spaces and return true for underscore, digits and alphabets.
In JavaScript, includes() method determines whether a string contains the given characters within it or not. This method returns true if the string contains the characters, otherwise, it returns false.
A few problems :
match
instead of test (not a bug but not the most efficient)inputtxt.value
but inputtxt
is yet the valueYou may use this :
function alphanumeric(inputtxt) {
var letters = /^[0-9a-zA-Z]+$/;
if (letters.test(inputtxt)) {
alert('accepted');
return true;
} else {
alert('Please input alphanumeric characters only');
return false;
}
}
You are using .value
twice:
document.getElementById("first_name").value
and if(inputtxt.value.match(letters))
Remove one of them.
You are using value
twice:
alphanumeric(document.getElementById("first_name").value);
and
if(inputtxt.value.match(letters))
This basically unfolds to
if(document.getElementById("first_name").value.value.match(letters))
which is meaningless since the String
object value
has no property value
, and the undefined
entity [...]value.value
has no property match()
(the debug console ought to tell you as much).
enter code here
var test = alphanumeric(document.getElementById("first_name"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With