javascript regex to allow at least one special character and one numeric

前端 未结 3 2080
天命终不由人
天命终不由人 2021-01-24 04:43

Im beginer about regex...I need to create a regular expression to check if a string has got at least one special character and one numeric. Im using ([0-9]+[!@#$%\\^&*

3条回答
  •  遇见更好的自我
    2021-01-24 05:19

    One simple way to check is to do 2 tests on the input string for the existence of each type of character:

    /[0-9]/.test(inputString) && /[special_characters]/.test(inputString)
    

    The code will do as you described: check if there is at least 1 digit, and at least 1 special character in the inputString. There is no limit on the rest of the inputString, though.

    Fill in special_characters with your list of special characters. In your case, it would be:

    /[0-9]/.test(inputString) && /[!@#$%^&*(){}[\]<>?/|.:;_-]/.test(inputString)
    

    I removed a few redundant escapes in your pattern for special character. (^ doesn't need escaping, and - is already there at the end).

    This make the code readable and less maintenance headache, compared to trying to write a single regex that do the same work.

提交回复
热议问题