Can I use Regex for this purpose?

I am trying to check the input field, making sure that only text, spaces and numbers can be entered. I thought the easiest way to do this is to use a regex by doing something like this:

function checkVal() {
var input = document.getElementById("input").value; 
if (input.match(/[a-zA-Z0-9]+$/) == null) {
    alert("error");
    }
}

In particular, I need to make sure that the underscore is not in this field (this is really important). From testing, this does not seem to work properly, but I think it is more important because I can use the regular expression for the wrong purpose, and not because it is syntactically incorrect.

Would it be easier if I wrote a function to exclude the underscore when entering this input field?

EDIT: just to make it a little clearer, I only want to accept letters, numbers and spaces.

+3
source share
3 answers

Remember to include the beginning of the line, ^(and space):

/^[a-zA-Z0-9 ]+$/
+6
source

try using this regex:

/^[a-zA-Z0-9 ]+$/

i for numbness:

EDIT:

/^[a-z0-9 ]+$/i
+2
source

This is not like your space check, also you check if the string ends only with numbers or characters.

Try the following:

function checkVal() {
var input = document.getElementById("input").value; 
if (input.match(/^[ a-zA-Z0-9]+$/) == null) {
    alert("error");
    }
}
0
source

All Articles