Alphanumeric, dash and underscore but no spaces regular expression check JavaScript

前端 未结 7 584
忘掉有多难
忘掉有多难 2020-12-23 10:48

Trying to check input against a regular expression.

The field should only allow alphanumeric characters, dashes and underscores and should NOT allow spaces.

相关标签:
7条回答
  • 2020-12-23 11:26

    Don't escape the underscore. Might be causing some whackness.

    0 讨论(0)
  • 2020-12-23 11:27

    try this one, it is working fine for me.

    "^([a-zA-Z])[a-zA-Z0-9-_]*$"
    
    0 讨论(0)
  • 2020-12-23 11:28

    However, the code below allows spaces.

    No, it doesn't. However, it will only match on input with a length of 1. For inputs with a length greater than or equal to 1, you need a + following the character class:

    var regexp = /^[a-zA-Z0-9-_]+$/;
    var check = "checkme";
    if (check.search(regexp) === -1)
        { alert('invalid'); }
    else
        { alert('valid'); }
    

    Note that neither the - (in this instance) nor the _ need escaping.

    0 讨论(0)
  • 2020-12-23 11:29

    Try this

    "[A-Za-z0-9_-]+"
    

    Should allow underscores and hyphens

    0 讨论(0)
  • 2020-12-23 11:31

    This syntax is a little more concise than the answers that have been posted to this point and achieves the same result:

    let regex = /^[\w-]+$/;
    
    0 讨论(0)
  • 2020-12-23 11:32

    You shouldn't use String.match but RegExp.prototype.test (i.e. /abc/.test("abcd")) instead of String.search() if you're only interested in a boolean value. You also need to repeat your character class as explained in the answer by Andy E:

    var regexp = /^[a-zA-Z0-9-_]+$/;
    
    0 讨论(0)
提交回复
热议问题