Check if the text field contains invalid characters

I have a problem trying to check if a text field contains only az values ​​0-9 using JavaScript.

I have a text box on my page:

<input type="text" id="first_name" class="first_name" value=""> 

I use the following JavaScript function to validate my text field:

 // 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 call my function as follows:

 var test = alphanumeric(document.getElementById("first_name").value); 

However, nothing happens.

If I warn 'inputtxt' in its alphanumeric function, it returns my value, which I have in my text box, so I know that there is a value that needs to be checked, but it does not seem to continue from here.

Does anyone know where I was wrong?

I am trying to do this using JavaScript (without jQuery).

+4
source share
3 answers

You use .value twice:

 document.getElementById("first_name").value 

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

Remove one of them.

+3
source

A few problems:

  • bad form for regular expression literal (do not use quotation marks for them)
  • using match instead of test (not an error, but not the most efficient)
  • you are using inputtxt.value , but inputtxt is still a value
  • you will never come back.

You can 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; } } 
+12
source

You use value twice:

 alphanumeric(document.getElementById("first_name").value); 

and

 if(inputtxt.value.match(letters)) 

It basically takes place before

 if(document.getElementById("first_name").value.value.match(letters)) 

which is pointless because the String value object does not have a value property, and the undefined [...]value.value does not have a match() property (the debug console should tell you the same).

enter code here var test = alphanumeric (document.getElementById ("first_name"));

0
source

All Articles