Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regex only alphabet, number and underscore

I want to check if a text box input is valid (only alphabet, numbers and underscores allowed. No whitespaces or dashes). I currently have this, but whitespaces & dashes seem to pass.

function validText(field)
{
    var re = /[a-zA-Z0-9\-\_]$/
    if (field.value.search(re) == -1)
    {
        alert ("Invalid Text");
        return false;
    }
}

A valid input would be something like

'Valid_Input123'

invalid

'Invalid-Input !'
like image 458
user1530318 Avatar asked Feb 04 '14 00:02

user1530318


People also ask

How do I allow only letters and numbers in regex?

In order to verify that the string only contains letters, numbers, underscores and dashes, we can use the following regex: "^[A-Za-z0-9_-]*$".

Can only contain letters numbers and underscores?

Usernames can only use letters numbers underscores and period.

How do I restrict only alphanumeric in Javascript?

another way would be [^\W_] but [a-z0-9] /i is a obvious way.

What is the regex for underscore?

The _ (underscore) character in the regular expression means that the zone name must have an underscore immediately following the alphanumeric string matched by the preceding brackets. The . (period) matches any character (a wildcard).


1 Answers

  1. The \w is a handy regex escape sequence that covers letters, numbers and the underscore character
  2. You should test the entire string for valid characters by anchoring the validity test at the start (^) and end ($) of the expression
  3. The regular expression test method is faster than the string search method
  4. You can also test for one or more characters using the + quantifier

To summarise (in code)

var re = /^\w+$/;
if (!re.test(field.value)) {
    alert('Invalid Text');
    return false;
}
return true;

Alternatively, you can test for any invalid characters using

/\W/.test(field.value)

\W being any character other than letters, numbers or the underscore character.

Then you might also need to add a length check to invalidate empty strings, eg

if (/\W/.test(field.value) || field.value.length === 0)
like image 114
Phil Avatar answered Oct 01 '22 23:10

Phil