milami
milami

Reputation: 39

Escaping a number of special characters in RegEx (JS)

I'm trying to validate password which has to contain at least

1 upper case

1 lower case

1 special character, namely one of these: ( ) [ ] { } ? ! $ % & / = * + ~ , . ; : < > - _

Here is my code:

function checkForm(){

        re = /[a-z]/;
        if (!re.test(myForm.passwd1.value)) {
            alert("Error: password must contain at least one lower case letter!");
            myForm.passwd1.focus();
            return false;
        }

        re = /[A-Z]/;
        if (!re.test(myForm.passwd1.value)) {
            alert("Error: password must contain at least one uppercase letter");
            myForm.passwd1.focus();
        return false;
        }
    }

I would like to add another part to my code regarding special characters. How do I pack them all in a regex? Which ones do I have to escape?

Upvotes: 0

Views: 73

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174796

You may use lookarounds.

^(?=.*?[a-z])(?=.*?[A-Z]).*[()\[\]{}?!$%&\/=*+~,.;:<>_-].*$

Upvotes: 2

Related Questions