Javascript Regex for Password Requirements

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
Pyrite
Forum Regular
Posts: 769
Joined: Tue Sep 23, 2003 11:07 pm
Location: The Republic of Texas
Contact:

Javascript Regex for Password Requirements

Post by Pyrite »

Hey, I need a Javascript function to be executed when a form is submitted to make sure the password matches the password requirements for my site.

The requirements are (Same as Windows Server 2003 AD):
At least 8 Chars in Length,
3 of the 4 conditions met:
Uppercase, Lowercase, Number, Special Chars.

I tried to get myself started, but I am dumb.

Code: Select all

function cpr() {
	var regex=/^A-Za-z0-9$/g;
	inputstr = document.regform.password1.value;
	if (!regex.test(inputstr)) {
		alert('Your Password Does Not Contain Upper or Lower or a Number');
	}
}
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

I think it'd be easier with 5 regexes.. 1 for the full match, and 1 for each of the character requirments... so something like

Code: Select all

function cpr(in)
{
  var pattern1 = /^їA-Za-z0-9whatever special chars]{8,}$/g;
  var pattern2 = /їA-Z]/;
  var pattern3 = /їa-z]/;
  var pattern4 = /ї0-9]/;
  var pattern5 = /їyour special chars again]/;
  var matchCount = 0;

  if(!pattern1.test(in)) alert('Your password isn''t valid.');
  if(pattern2.test(in)) matchCount++;
  if(pattern3.test(in)) matchCount++;
  if(pattern4.test(in)) matchCount++;
  if(pattern5.test(in)) matchCount++;
  if(matchCount < 3) alert('You are missing a required character type.');
  else return true;
  return false;
&#125;
Post Reply