Aaron
Aaron

Reputation: 3639

Check if textbox contains invalid characters

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).

Upvotes: 8

Views: 32073

Answers (3)

Chris
Chris

Reputation: 4372

You are using .value twice:

document.getElementById("first_name").value

and if(inputtxt.value.match(letters))

Remove one of them.

Upvotes: 5

Manishearth
Manishearth

Reputation: 16188

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 herevar test = alphanumeric(document.getElementById("first_name"));

Upvotes: 1

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382102

A few problems :

  • a bad form for the regular expression literal (don't use quotes for them)
  • the use of match instead of test (not a bug but not the most efficient)
  • you use inputtxt.value but inputtxt is yet the value
  • you never return true

You 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;
  }
}

Upvotes: 18

Related Questions