Search code examples
javascripthtmlezpublish

Checking if string contains number and symbol


I am working on an account creation site for a college.

My problem is that I want to return error messages if the password the user is setting doesn't contain numbers and/or symbols, and I need help.

The password needs to contain higher and lower case letters, a number and a symbol (!, #, % or &). I need the error messages to be specific.

Any suggestions? I am using HTML and JS.


Solution

  • I would suggest using Regex and running a check on each

    Like so:

    function validateStr(str) {
        var regex = new RegExp("[A-Z]+"); // Check for uppercase first   
        if(regex.test(str) == true) {
            regex = new RegExp("[0-9]+"); // Now we check for numbers   
            if(regex.test(str) == true) {
                regex = new RegExp("[a-z]+"); // checking now for lowercase
                if(regex.test(str) == true) {
                    return 1;   
                } else return 2;
            } else return 3;
        } else return 4;
    }
    

    I haven't included the "Special Character" parameter because you have to include those individually in to one regular expression which I don't recommend you do. I am struggling to get it to work on JSFiddle so I haven't included one but just post a comment if you need me to explain further.