Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);

    }
like image 648
pixelbobby Avatar asked Apr 05 '12 15:04

pixelbobby


1 Answers

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 &

like image 189
rgvcorley Avatar answered Oct 02 '22 19:10

rgvcorley