简体   繁体   中英

Regex String Doesn't Start or End With Special Character

SO buddies, greetings. I have some password requirements I need to implement and one of the requirements is the string cannot start or end with a special character . I did spend some time Googling around but my RegEx kung-fu is kimosabe level.

Just in case you're interested in some code, here's the JavaScript :
Note: Yes, passwords are also validated on the server as well:) The following snippet runs the RegEx tests and simply checks or x's the row item associated with the password rule.

var validate = function(password){
        valid = true;

        var validation = [
            RegExp(/[a-z]/).test(password), RegExp(/[A-Z]/).test(password), RegExp(/\d/).test(password), 
            RegExp(/[-!#$%^&*()_+|~=`{}\[\]:";'<>?,./]/).test(password), !RegExp(/\s/).test(password), !RegExp("12345678").test(password), 
            !RegExp($('#txtUsername').val()).test(password), !RegExp("cisco").test(password), 
            !RegExp(/([a-z]|[0-9])\1\1\1/).test(password), (password.length > 7)
        ]

        $.each(validation, function(i){
            if(this == true)
                $('.form table tr').eq(i+1).attr('class', 'check');
            else{
                $('.form table tr').eq(i+1).attr('class', '');
                valid = false
            }
        });

        return(valid);

    }

EDIT: The regular expression you want is:-

/^[a-zA-Z0-9](.*[a-zA-Z0-9])?$/

Additional information

In regular expressions ^ means 'beginning of string' and $ means 'end of string', so for example:-

/^something$/

Matches

'something'

But not

'This is a string containing something and some other stuff'

You can negate characters using [^-char to negate-] , so

/^[^#&].*/

Matches any string that doesn't begin with a # or a &

/^[a-zA-Z0-9](.*[a-zA-Z0-9])?$/

This expression checks the following validations:

  • No blank spaces at start and end
  • No special characters at the end and beginning
  • special characters allowed in between

This regex should be what you want:

/^[0-9a-z].*[0-9a-z]$/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM