admin管理员组

文章数量:1331598

I want to accept only letters, numbers, and hyphen (dash) in the input. in php, i do this:

if(!preg_match("/^[A-Za-z0-9-]+$/", $input)) {
    echo "Only letters, numbers, and hyphens are allowed.";
}

how can I achieve this same thing in vanilla javascript? if its not possible in pure javascript, how can i do it in jquery? thanks

I want to accept only letters, numbers, and hyphen (dash) in the input. in php, i do this:

if(!preg_match("/^[A-Za-z0-9-]+$/", $input)) {
    echo "Only letters, numbers, and hyphens are allowed.";
}

how can I achieve this same thing in vanilla javascript? if its not possible in pure javascript, how can i do it in jquery? thanks

Share asked Jul 5, 2017 at 18:21 Jason BaleJason Bale 3632 gold badges7 silver badges14 bronze badges 4
  • Possible duplicate of jQuery only allow numbers,letters and hyphens – Jedi Commented Jul 5, 2017 at 18:24
  • @Jedi i'm asking for vanilla javascript. – Jason Bale Commented Jul 5, 2017 at 18:25
  • The last - should be escaped: [A-Za-z0-9\-] you can short it to this: /^[a-z\d\-]+$/i (i to ignore case sensitivity and \d for digits). And you should use .test to test not match, it's better. – ibrahim mahrir Commented Jul 5, 2017 at 18:33
  • 2 @ibrahimmahrir: No need to escape dash at the beginning or end of the character class as it doesn't denote a range. – AbraCadaver Commented Jul 5, 2017 at 18:40
Add a ment  | 

2 Answers 2

Reset to default 3

Adapted from Sylvain's answer here: jQuery only allow numbers,letters and hyphens.

Note: jQuery is pretty much a wrapper for vanilla js to make a lot of mon statements like Document.querySelectorAll() shorter, it's generally safe to assume that jQuery can be directly converted to vanilla js (I can't think of any examples off the top of my head where the jQuery functionality differs).

What you could do is select all the inputs in a form (or whichever you would like), then test their values against a regex (Sylvain used a regex that selects the inverse of the desired characters so that it would be true if there is an invalid character) and if it has any forbidden character prevent the form from submitting and do some other things asking the user to address the issue.

document.getElementById("formWhitelistedChars").addEventListener("submit", function(e) {
    // Get all inputs in the form we specifically are looking at, this selector can be
    // changed if this is supposed to be applied to specific inputs
    var inputs = document.querySelectorAll('#formWhitelistedChars input');
    var forbiddenChars = /[^a-z\d\-]/ig;
    
    // check all the inputs we selected
    for(var input of inputs) {
        // Just in case the selector decides to do something weird
        if(!input) continue;
        
        // Check that there aren't any forbidden chars
        if(forbiddenChars.test(input.value)) {
            // This line is just to do something on a failure for Stackoverflow
            // I suggest removing this and doing something different in application
            console.log('input ' + input.name + ' has forbidden chars.');
            
            // Do stuff here

            // Prevent submit even propagation (don't submit)
            e.preventDefault();
            return false;
        }
    }
});
<form id="formWhitelistedChars">
  <input name="1" />
  <input name="2" />
  <button type="submit">Submit</button>
</form>

EDIT: Replaced 0-9 with \d as @ibrahimmahrir mentioned in the ments

EDIT2: Changed input listeners to form submit

You can start a new regex using /{criteria}/{flags}. Your regex would translate to something like this:

/^[aA-zZ0-9-]+$/g.test(/* value to test here*/)

本文标签: javascriptAllow only lettersnumbersand hyphen in inputStack Overflow