Reputation: 590
I know its good to use serverside validation for security, except this is just to get my head around validation.
My efforts so far have amounted to the following
function validateUser()
{
var x=document.forms["myForm"]["email"].value;
var y=document.forms["myForm"]["password"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
var uppercase = password.match(/[A-Z]/)
var lowercase = password.match(/[a-z]/g)
var number = password.match(/[0-9]/g)
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address or password");
return false;
}else{
alert("Valid Email Address and Password");
return true;
}
}
Basically, I need an alert box to pop up when the password doesn't have at least 1 lowercase, uppercase and a number. So far my code is just throwing an error when the email is in the wrong format. What do I add to the if statement to check the password characters?
Thanks in advance,
James
Upvotes: 0
Views: 6870
Reputation: 351
Few issues we have in your current implementation:
a. The error you're likely getting is that password is undefined.
Right now you're doing:
var y=document.forms["myForm"]["password"].value;
but you refer to it as "password" further on:
var uppercase = password.match(/[A-Z]/)
var lowercase = password.match(/[a-z]/g)
change the var y to:
var password=document.forms["myForm"]["password"].value;
b. To validate email, you should use a Regex such as:
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var isValidEmail = re.test(email);
c. To check for the password rules, you should just rely on the regular expressions you have in place already (and strip out the atpos, dotpos usage - that makes it much more complicated than it even needs to be).
Example:
var email='me@mailinator.com';
var password='test-P1assword';
var hasUpper = password.match(/[A-Z]/)
var hasLower = password.match(/[a-z]/g)
var hasNumber = password.match(/[0-9]/g)
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var isValidEmail = re.test(email);
if (isValidEmail && hasUpper && hasLower && hasNumber) {
alert("Valid Email Address and Password");
return true;
} else {
alert("Not a valid e-mail address or password");
return false;
}
JSFiddle example, complete with Regex to validate email AND password: http://jsfiddle.net/4hH3T/2/
The regex was taken from: Validate email address in JavaScript?
Upvotes: 2
Reputation: 15881
you can use regex to validate.
var reg=/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*(_|[^\w])).+$/;
var isValid=reg.test(inputemail);
Upvotes: 0