0

I am trying to validate the password using regex with function but its not working for me. can anyone take a look at what is missing or what mistake i have made.?

Here is my code:

 function passCheck() {
    var passexp = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/;
    var password = document.getElementById("password");
    
    if (password != "") {
        if (!password.match(passexp)) {
            document.registration.password.focus();
            document.getElementById('error2').innerHTML = "Password should be atleast 8 character long and must contain at least one digit,at least one lower case,at least one upper case.";
            return false;
        } else {
            document.getElementById('error2').innerHTML = "";
            return true;
        }
    } else {
        document.registration.password.focus();
        document.getElementById('error2').innerHTML = "Password can't be blank";
        return true;
    }
}
<label for="password">* Password </label>
<input type="password" name="password" placeholder="Password should be atleast 8 characters" id="password" size="40" required="required" onblur="return passCheck();"/>
<span id="error2"></span>

EDIT:

Hello,

In same form I have few other fields(viz. name,email,password,confirm password,username,mobile no, street, city, country(Select tag), gender(radio button). and now my questions are or rather confusions are:

  1. do I need to check if the field is empty(on both client side and server side) in spite of using 'required' attribute?

  2. I have created new function for each of the field i am trying to validate(just like passCheck() which makes code unnecessarily lengthy. So here re-usability of code is not done. In what other way I can implement validation so as to achieve it. Its bit boring too to implement similar kind of logic or methods again and again with minor changes.

  3. Javascript variable can not have same name as that of function name which contains that variable.? Why? Because when I was trying to use same name,code didn't worked. But when I checked same code on jsfiddle.net it showed me an error for that variable.

  4. Whats the purpose of using PHP functions like mysql_real_escape_string() for non text fields(select box and radio button). Here we are not allowing user to enter anything else but the already defined options only.

  5. Is it good practice to keep one radio button checked for gender.?

  6. I am storing gender in database as CHAR(1) which stores first character of Male/Female. How to store same using ENUM.?

7
  • Can it contain only lower/ uppercase letters and numbers? Or can it also contain special characters as well? Commented Sep 19, 2014 at 7:01
  • @Mercury yes. it should contain special characters as well Commented Sep 19, 2014 at 7:04
  • @AvinashRaj yes. at least one digit, one lower case, one upper case,one special chars and min length 8 Commented Sep 19, 2014 at 7:08
  • Isn't there an attribute you can provide to <input> elements such that the checks are carried out by the browser instead of writing a procedure oneself? Commented Sep 19, 2014 at 7:10
  • 2
    “Not working” is not a problem description. Does it crash a browser? Turn the page to pink? Reject passwords you meant to accept? Accept passwords that you meant to reject? What did you mean to accept? Commented Sep 19, 2014 at 7:21

4 Answers 4

2

This:

var password = document.getElementById("password");

if (password != "") {

...assigns the HTML password input to the password variable, not the value of that input. (password != "") will always be true because password is not a string, it's a form element.

Try this instead:

var password = document.getElementById("password").value;
Sign up to request clarification or add additional context in comments.

1 Comment

No problem, easy mistake to make :)
2

Below is a regular expression you can try.

"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$"

The above regex will enforce these rules:

  1. At least one upper case Alphabet
  2. At least one lower case Alphabet
  3. At least one digit
  4. Minimum 8 in length

    "^(?=.[a-z])(?=.[A-Z])(?=.\d)(?=.[$@$!%?&])[A-Za-z\d$@$!%?&]{8,}"

The above regex will enforce these rules:

  1. At least one upper case Alphabet
  2. At least one lower case Alphabet
  3. At least one digit
  4. One Special character
  5. Minimum 8 in length

Also Check Steve's answer regarding the form not working.

Comments

1

You need to make the distinction between the <input> element and the value it contains. The following snippet contains a few changes to your original code. In particular, the variable passwordValue contains the text content of the <input>, whereas passwordElement is the input itself. I also added in a .trim() to your test for whether the input is blank, as this catches input consisting of only whitespace before doing the regex match.

function passCheck() {
    var passexp = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/;
    var passwordElement = document.getElementById("password");
    var passwordValue = passwordElement.value;
    if (passwordValue.trim() !== "") {
        if (!passwordValue.match(passexp)) {
            passwordElement.focus();
            document.getElementById('error2').innerHTML = "Password should be atleast 8 character long and must contain at least one digit,at least one lower case,at least one upper case.";
            return false;
        } else {
            document.getElementById('error2').innerHTML = "";
            return true;
        }
    } else {
        passwordElement.focus();
        document.getElementById('error2').innerHTML = "Password can't be blank";
        return true;
    }
}
<label for="password">* Password </label>
<input type="password" name="password" placeholder="Password should be atleast 8 characters" id="password" size="40" required="required" onblur="passCheck()"/>
<span id="error2"></span>

As you asked in the comments about the !== operator, here is some explanation:

!== is the opposite operator to ===, which means that it does a strict comparison between the left hand side and the right hand side. This means that the type of the variable is important, as well as the value. For example 2 == "2" will evaluate to true, whereas 2 === "2" will evaluate to false. It is generally regarded as good practice to use the strict comparison as it communicates what you are trying to do more effectively. I changed != to !== in your code for this reason; it is not directly related to fixing your problem.

2 Comments

its doing as expected now. thank you. can you please elaborate how changing of "!=" to "!==" affects the flow. What is the difference between them?
No problem. I have added some explanation to my answer.
1

Just change your regex to,

^(?=.{8,})(?=.*?\d)(?=.*?[A-Z])(?=.*[a-z]).*?(?:(?!\s|\n)\W).*$

(?:(?!\s|\n)\W) ensures that the one character must be a non-word character but not of space or newline character.

DEMO

And this won't allow spaces or newline characters inside the password text box,

^(?=.{8,})(?=.*?\d)(?=.*?[A-Z])(?=.*[a-z])(?:(?!\s|\n)[\W\w])*$

DEMO

1 Comment

thanks. I tried it but it doesnt seem to be working and now i believe there must be mistake in code (not in regex).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.