Introduction
If we want to force a password to be a combination of alphabets and numbers and force a range of chars, we can simply do it in JavaScript.
Background
Simply use JavaScript to make sure that the user enters a combination of alphanumeric data and check for a minimum number of chars and maximum allowed chars.
This code checks for at least one alphabetic char and one numeric char.
Using the code
function validatePassword(fieldName,minNumberOfDigits, maxNumberOfDigits) {
var alphaNumericPattern = "^[a-z0-9/_/$]{" +
minNumberOfDigits + "," + maxNumberOfDigits + "}";
var regExpr = new RegExp(alphaNumericPattern,"i");
var sourceField = event != null ? event.srcElement:e.target;
if(fieldName != null && fieldName != "null" && fieldName != "undefined") {
sourceField = document.getElementById(fieldName);
}
var message = "Password must be a combination of alphabets and numbers";
message = message + "\n and must be between " + minNumberOfDigits +
" and " + maxNumberOfDigits + " chars.";
var sourceFieldValue = sourceField.value;
if(sourceFieldValue.length < minNumberOfDigits ||
sourceFieldValue.length > maxNumberOfDigits){
alert(message);
sourceField.focus();
return false;
}
if (!regExpr.test(sourceFieldValue)) {
alert(message);
sourceField.focus();
return false;
}
regExpr = new RegExp("[a-z/_/$]{1}","i");
if(!regExpr.test(sourceFieldValue)){
alert(message);
sourceField.focus();
return false;
}
regExpr = new RegExp("[0-9]{1}","i");
if(!regExpr.test(sourceFieldValue)){
alert(message);
sourceField.focus();
return false;
}
}
var alphaNumericPattern = "^[a-z0-9/_/$]{" + minNumberOfDigits +
"," + maxNumberOfDigits + "}";
It checks for any one of the following: a-z or 0-9 or _ or $. If the user enters anything other than the supported chars, it will alert the user.
At the same time, it makes sure that it meets the minimum number of chars and the maximum allowed chars.
regExpr = new RegExp("[a-z/_/$]{1}","i");
It checks for at least one alphabetic char:
regExpr = new RegExp("[0-9]{1}","i");
and it checks for atl east one number.
If it fails any one of the checks, it will alert the user and set the focus back on to the source field.
So you would assign this function on the onchage
or onblur
event.
<input type="password" onblur="return validatePassword(,6,12)">
or:
<input type="password" onchange="return validatePassword('null',6,12)">
Note: It is always advisable to double check the data before you insert or store it somewhere. You need to use server side validation to make the data foolproof.
Do not just rely on JavaScript validations.