javascript regex for special characters

前端 未结 12 677
囚心锁ツ
囚心锁ツ 2020-11-29 22:28

I\'m trying to create a validation for a password field which allows only the a-zA-Z0-9 characters and .!@#$%^&*()_+-=

I can\'t seem to

相关标签:
12条回答
  • 2020-11-29 22:45

    a sleaker way to match special chars:

    /\W|_/g
    

    \W Matches any character that is not a word character (alphanumeric & underscore).

    Underscore is considered a special character so add boolean to either match a special character or _

    0 讨论(0)
  • 2020-11-29 22:45

    Complete set of special characters:

    /[\!\@\#\$\%\^\&\*\)\(\+\=\.\<\>\{\}\[\]\:\;\'\"\|\~\`\_\-]/g
    

    To answer your question:

    var regular_expression = /^[A-Za-z0-9\!\@\#\$\%\^\&\*\)\(+\=\._-]+$/g
    
    0 讨论(0)
  • 2020-11-29 22:45

    Regex for minimum 8 char, one alpha, one numeric and one special char:

    /^(?=.*[A-Za-z])(?=.*\d)(?=.*[!@#$%^&*])[A-Za-z\d!@#$%^&*]{8,}$/
    
    0 讨论(0)
  • 2020-11-29 22:46
    function nameInput(limitField)
    {
    //LimitFile here is a text input and this function is passed to the text 
    onInput
    var inputString = limitField.value;
    // here we capture all illegal chars by adding a ^ inside the class,
    // And overwrite them with "".
    var newStr = inputString.replace(/[^a-zA-Z-\-\']/g, "");
    limitField.value = newStr;
    }
    

    This function only allows alphabets, both lower case and upper case and - and ' characters. May help you build yours.

    0 讨论(0)
  • 2020-11-29 22:47

    What's the difference?

    /[a-zA-Z0-9]/ is a character class which matches one character that is inside the class. It consists of three ranges.

    /a-zA-Z0-9/ does mean the literal sequence of those 9 characters.

    Which chars from .!@#$%^&*()_+-= are needed to be escaped?

    Inside a character class, only the minus (if not at the end) and the circumflex (if at the beginning). Outside of a charclass, .$^*+() have a special meaning and need to be escaped to match literally.

    allows only the a-zA-Z0-9 characters and .!@#$%^&*()_+-=

    Put them in a character class then, let them repeat and require to match the whole string with them by anchors:

    var regex = /^[a-zA-Z0-9!@#$%\^&*)(+=._-]*$/
    
    0 讨论(0)
  • 2020-11-29 22:48

    this is the actual regex only match:

    /[-!$%^&*()_+|~=`{}[:;<>?,.@#\]]/g
    
    0 讨论(0)
提交回复
热议问题