How to Check Password validation dynamically using jquery/javascript? - javascript

Kindly read my question fully before assign my one as duplicate.
Hi I tried to verify password dynamically during keypress. Actually it is working for me while enter the password. But When I delete the password only 2 conditions satisfies. My code and images below:
My password box html code is
<div class="form-group has-feedback">
<input class="form-control" id="NewPassword" placeholder="New Password" onkeypress="EnterPassword()" onkeydown="DeletePassword()" type="password">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
I used glyphicon-remove infront of each conditions for the password. When I enter the password each icon change to glyphicon-ok if the condition satisfies.
These are my password conditions with icon:
Lets assume my password as Password#123, it contains all my required things, so all the icons changed to ok.
But when I delete the password only 2 of the conditions satisfied.
Codes for the function below:
<script type="text/javascript" >
function EnterPassword() {
$("#NewPassword").keyup(function () {
var regex1 = new Array();
var regex2 = new Array();
var regex3 = new Array();
var regex4 = new Array();
regex1.push("[A-Z]"); //Uppercase Alphabet.
regex2.push("[a-z]"); //Lowercase Alphabet.
regex3.push("[0-9]"); //Digit.
regex4.push("[!###$%^&*]"); //Special Character.
if ($(this).val().length>6) {
$("#Length").removeClass("glyphicon glyphicon-remove").addClass("glyphicon glyphicon-ok");
}
for (var i = 0; i < regex1.length; i++) {
if (new RegExp(regex1[i]).test($(this).val())) {
$("#UpperCase").removeClass("glyphicon glyphicon-remove").addClass("glyphicon glyphicon-ok");
}
}
for (var i = 0; i < regex2.length; i++) {
if (new RegExp(regex2[i]).test($(this).val())) {
$("#LowerCase").removeClass("glyphicon glyphicon-remove").addClass("glyphicon glyphicon-ok");
}
}
for (var i = 0; i < regex3.length; i++) {
if (new RegExp(regex3[i]).test($(this).val())) {
$("#Numbers").removeClass("glyphicon glyphicon-remove").addClass("glyphicon glyphicon-ok");
}
}
for (var i = 0; i < regex4.length; i++) {
if (new RegExp(regex4[i]).test($(this).val())) {
$("#Symbols").removeClass("glyphicon glyphicon-remove").addClass("glyphicon glyphicon-ok");
}
}
});
}
function DeletePassword() {
$("#NewPassword").keyup(function () {
var regex1 = new Array();
var regex2 = new Array();
var regex3 = new Array();
var regex4 = new Array();
regex1.push("[A-Z]"); //Uppercase Alphabet.
regex2.push("[a-z]"); //Lowercase Alphabet.
regex3.push("[0-9]"); //Digit.
regex4.push("[!###$%^&*]"); //Special Character.
var thisVal =$(this).val();
if ($(this).val().length<6) {
$("#Length").removeClass("glyphicon glyphicon-ok").addClass("glyphicon glyphicon-remove");
}
for (var i = 0; i < regex1.length; i++) {
if (new RegExp(regex1[i]).test(!thisVal)) {
$("#UpperCase").removeClass("glyphicon glyphicon-ok").addClass("glyphicon glyphicon-remove");
}
}
for (var i = 0; i < regex2.length; i++) {
if (new RegExp(regex2[i]).test(!thisVal)) {
$("#LowerCase").removeClass("glyphicon glyphicon-ok").addClass("glyphicon glyphicon-remove");
}
}
for (var i = 0; i < regex3.length; i++) {
if (new RegExp(regex3[i]).test(!thisVal)) {
$("#Numbers").removeClass("glyphicon glyphicon-ok").addClass("glyphicon glyphicon-remove");
}
}
for (var i = 0; i < regex4.length; i++) {
if (new RegExp(regex4[i]).test(!thisVal)) {
$("#Symbols").removeClass("glyphicon glyphicon-ok").addClass("glyphicon glyphicon-remove");
}
}
});
}
</script>
NOTE: UpperCase,LowerCase,Numbers,Symbols are the Id name that I gave to the tag where I used the glyphicon remove icon.
If my codes not working completely means my question may comes under duplicate. But Its Partially working, So kindly let me know if there is any mistake I did on my code.
Thanks in Advance

We can simplify your code a lot.
For a start instead of using inline event handlers we will use jQuery's .on to bind the event.
Next we'll consolidate your rules into a JSON object array with the rules target.
We then iterate the Regex based rules adding and removing classes as required
/*Actual validation function*/
function ValidatePassword() {
/*Array of rules and the information target*/
var rules = [{
Pattern: "[A-Z]",
Target: "UpperCase"
},
{
Pattern: "[a-z]",
Target: "LowerCase"
},
{
Pattern: "[0-9]",
Target: "Numbers"
},
{
Pattern: "[!###$%^&*]",
Target: "Symbols"
}
];
//Just grab the password once
var password = $(this).val();
/*Length Check, add and remove class could be chained*/
/*I've left them seperate here so you can see what is going on */
/*Note the Ternary operators ? : to select the classes*/
$("#Length").removeClass(password.length > 6 ? "glyphicon-remove" : "glyphicon-ok");
$("#Length").addClass(password.length > 6 ? "glyphicon-ok" : "glyphicon-remove");
/*Iterate our remaining rules. The logic is the same as for Length*/
for (var i = 0; i < rules.length; i++) {
$("#" + rules[i].Target).removeClass(new RegExp(rules[i].Pattern).test(password) ? "glyphicon-remove" : "glyphicon-ok");
$("#" + rules[i].Target).addClass(new RegExp(rules[i].Pattern).test(password) ? "glyphicon-ok" : "glyphicon-remove");
}
}
/*Bind our event to key up for the field. It doesn't matter if it's delete or not*/
$(document).ready(function() {
$("#NewPassword").on('keyup', ValidatePassword)
});
.glyphicon-remove {
color: red;
}
.glyphicon-ok {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="form-group has-feedback">
<input class="form-control" id="NewPassword" placeholder="New Password" type="password">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div id="Length" class="glyphicon glyphicon-remove">Must be at least 7 charcters</div>
<div id="UpperCase" class="glyphicon glyphicon-remove">Must have atleast 1 upper case character</div>
<div id="LowerCase" class="glyphicon glyphicon-remove">Must have atleast 1 lower case character</div>
<div id="Numbers" class="glyphicon glyphicon-remove">Must have atleast 1 numeric character</div>
<div id="Symbols" class="glyphicon glyphicon-remove">Must have atleast 1 special character</div>

i give you simple example.
Html
<!DOCTYPE HTML>
<html>
<head>
<title>Password strength checker in jQuery</title>
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script><!-- jQuery Library-->
<link rel="stylesheet" href="css/passwordscheck.css" /><!-- Include Your CSS file here-->
<script src="js/passwordscheck.js"></script><!-- Include Your jQUery file here-->
</head>
<body>
<div id="container">
<div id="header">
<h2>Password Strength Checking with jQuery</h2>
<hr>
</div>
<div id="content">
<form id="register">
<label for="password"><b>Password : </b></label>
<input name="password" id="password" type="password" placeholder="Type Your Password here"/>
<span id="result"></span>
</form>
</div>
</div>
</body>
</html>
JS
$(document).ready(function() {
$('#password').keyup(function() {
$('#result').html(checkStrength($('#password').val()))
})
function checkStrength(password) {
var strength = 0
if (password.length < 6) {
$('#result').removeClass()
$('#result').addClass('short')
return 'Too short'
}
if (password.length > 7) strength += 1
// If password contains both lower and uppercase characters, increase strength value.
if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) strength += 1
// If it has numbers and characters, increase strength value.
if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/)) strength += 1
// If it has one special character, increase strength value.
if (password.match(/([!,%,&,#,#,$,^,*,?,_,~])/)) strength += 1
// If it has two special characters, increase strength value.
if (password.match(/(.*[!,%,&,#,#,$,^,*,?,_,~].*[!,%,&,#,#,$,^,*,?,_,~])/)) strength += 1
// Calculated strength value, we can return messages
// If value is less than 2
if (strength < 2) {
$('#result').removeClass()
$('#result').addClass('weak')
return 'Weak'
} else if (strength == 2) {
$('#result').removeClass()
$('#result').addClass('good')
return 'Good'
} else {
$('#result').removeClass()
$('#result').addClass('strong')
return 'Strong'
}
}
});
Reference : Link
one of the best example for you
i hope you understand.

Related

How to filling table cells with random numbers through button in JavaScript

[User may enter number of rows and columns, then chess board appears after clicking enter button.][The problem is I cannot fill the table cells with random numbers using Fill button]
So far the code of JavaScript is
var a, b, tableElem, rowElem, colElem;
function createTable() {
a = document.getElementById('row').value;
b = document.getElementById('column').value;
if (a == "" || b == "") {
alert("Enter a number");
} else {
tableElem = document.createElement('table');
for (var i = 0; i < a; i++) {
rowElem = document.createElement('tr');
for (var j = 0; j < b; j++) {
colElem = document.createElement('td');
rowElem.appendChild(colElem);
if (i % 2 == j % 2) {
colElem.className = "white";
} else {
colElem.className = "black";
}
}
tableElem.appendChild(rowElem);
}
document.body.appendChild(tableElem);
}
}
and Html is
<div class="form-inline">
<div class="form-group">
<input type="text" class="form-control" id="row" placeholder="Row">
</div>
<div class="form-group">
<input type="text" class="form-control" id="column" placeholder="Column">
</div>
<button type="button" class="btn btn-primary" onclick="createTable()">
Enter
</button>
<button onclick="fillTable()" id="btn" type="button" class="btn btn-info">
Fill
I used jQuery
$(document).ready(function () {
$('#btn').click(function () {
$(colElem).append(1);
});
});
but with this code only bottom right corner is filled. Please can you give info how to fill all cells of the table with random number via Fill button
$(colElem) selector pointing to the last cell of the table... you need to select each and every cell and assign the random number... look into the below code (it will add random number between 0 to 99) to solve the issue... remove onclick="fillTable()" from the button..
$('#btn').click(function () {
$(tableElem).find("td").each(function(){
$(this).html(Math.floor(Math.random() * 100));
});
});

How to limit the amount of times an element can be created

Is there a way to limit the amount of times a user can click a button to create an element? This is what I have managed to put together so far. Thank you.
JavaScript
var ClickCount = 0;
function countClicks() {
var clickLimit = 8 ; //Max number of clicks
if(ClickCount<=clickLimit) {
populateTipItem();
}
else if(ClickCount > clickLimit)
{
return;
}
}
// TIP LIST
function populateTipItem() {
var x = document.createElement("INPUT");
x.setAttribute("type", "text");
x.setAttribute("class", "form-control mt-1 tip-item");
x.setAttribute("placeholder", "Another Tip Item! ... 250tks");
document.getElementById("tipList").appendChild(x);
}
HTML
<div id="tipList" class="form-group mt-5">
<label for="tips">Your Tip Menu Items</label>
<small class="form-text text-muted">Max 10 items.</small>
<input type="text" name="tips" class="form-control mt-1 tip-item" placeholder="Tip Item! ... 10tks"/>
</div>
<button class="btn btn-secondary" onclick="return countClicks()">Add Tip Item</button>
You're almost completed. The main change is to add ClickCount++ so you'll know how much elements were created.
var ClickCount = 0;
var clickLimit = 8 ; //Max number of clicks
function countClicks() {
if(ClickCount<=clickLimit) {
ClickCount++;
populateTipItem();
}
else if(ClickCount > clickLimit) {
return;
}
}
alternatively you can count the number of elements created:
var clickLimit = 8;
var tipList = document.getElementById('tipList');
function countClicks() {
if (tipsList.children.length < clickLimit) {
populateTipItem();
}
}

Form validation backwards compatible with earlier versions of IE

I know this is an on going concern in IT these days with different versions of IE being used between different machines, but I was wondering if someone might be able to advise me on how to successfully make this code (which works fine for all my form validation in IE 10, FireFox, Chrome, etc) work in earlier versions of IE.
The version I am testing it against is IE7.
function validate(form){
var p = form.getElementsByTagName("p");
var valid = true;
for(var i = 0; i < p.length; i++){
var inputs = p[i].getElementsByTagName("*");
if(p[i].className == "required" || p[i].className == "required error"){
for(var n = 0; n < inputs.length; n++){
switch(inputs[n].tagName){
case "INPUT":
if(inputs[n].value.trim() == "" || inputs[n].value == null){
if(+navigator.sayswho[1] < 9){
//JavaScript for IE version 8 and below
}
else{
inputs[n].className = inputs[n].className.replace( /(?:^|\s)error(?!\S)/ , "" );
inputs[n].className = inputs[n].className+" error";
p[i].className = "required error";
}
valid = false;
}
break;
case "SELECT":
if(inputs[n].options[inputs[n].selectedIndex].value == 0 || select.value == null){
if(+navigator.sayswho[1] < 9){
//JavaScript for IE version 8 and below
}
else{
inputs[n].className = inputs[n].className.replace( /(?:^|\s)error(?!\S)/ , "" );
inputs[n].className = inputs[n].className+" error";
p[i].className = "required error";
}
valid = false;
}
break;
}
}
}
}
if(valid){
var elements = form.getElementsByTagName("*");
for(var i = 0; i < elements.length; i++){
switch(elements[i].type){
case "submit":
elements[i].disabled = true;
break;
case "reset":
elements[i].disabled = true;
break;
case "button":
elements[i].disabled = true;
break;
}
}
return true;
}
return false;
}
+navigator.sayswho[1] is a value from another question I found on here that returns an int representing the browser's version (in this case 7)
An example of a form field is:
<p class="required">
<span>Required Field</span>
<input type="text" id="username" name="username" class="logon_field" onfocus="clearError(this)" placeholder="Username" autofocus />
</p>
The method is called using validate(this) in the form's onsubmit attribute
Thanks in advance!
Ah.. doing some looking here on SO. Seems there are some issues with getElementsByClassName and IE7.
getElementsByName in IE7
I'd solve it by breaking things into a couple of different pieces, shown below.
Free bonus, BTW. 'addClass' 'removeClass' and 'hasClass'
It is better to put the required attribute (or the class) on the input field itself, rather than on the wrapper... though you can set the wrapper's class to show the field is in error.
<doctype html>
<html>
<head>
<title>
Test page
</title>
<script>
function hasClass(ele,cls) {
return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
function addClass(ele,cls) {
if (!this.hasClass(ele,cls)) ele.className += " "+cls;
}
function removeClass(ele,cls) {
if (hasClass(ele,cls)) {
var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
ele.className=ele.className.replace(reg,' ');
}
}
function clearError(element) {
}
function validate(form) {
var i, l;
var input;
// First, let's check the input fields
var inputs = form.getElementsByTagName("input");
for (i = 0; i < inputs.length; i++) {
input = inputs[i];
// Skip stuff we don't want.
// You'll want password this list yet.
if (input.type !== "text") {
continue;
}
if (input.required || hasClass(input, "required")) {
if (input.value == "") {
alert(input.name + " is required");
}
}
}
}
</script>
</head>
<body>
<form action="#" onsubmit="validate(this); return false">
<p>
<label for="username">Required Field</label>
<input type="text" class="required" id="username" name="username" class="logon_field" onfocus="clearError(this)" placeholder="Username" autofocus />
</p>
<p>
<label for="trivia">Trivia Question</trivia>
<input type="text" id="trivia" name="trivia" class="" onfocus="clearError(this)" placeholder="Username" autofocus />
</p>
<input type="submit">
</form>
</body>
</html

date validation in javascript using .js files

I am having a ini.jsp page for creating a form for adding two text fields to input date and then using javascript in the ini.jsp page itself to validate those dates. I now have some library files(calendar.js, calendar-en.js, calendar-setup.js, calendar_1.png, calendar_system.css).
Now my question is how to I link these files to javascript (I am using ECLIPSE IDE) so that it displays calendar beside the textboxes for date in the format dd/mm/yyyy. . .
I have gone through lots of stuff, tried doing those but really couldn't get the expected output.
Below is the code that i have implemented so far
<html lang="en">
<head>
<style type="text/css" src="../datePickers/calendar-system.css">
</style>
</head>
<body>
<script language="Javascript" src="../Scripts/calendar.js"></script>
<h1>Report Generation</h1>
<div style="margin: 0 auto; width: 100%; text-align: left">
<form name="date" action="<c:url value="cli.htm"/>"
method="post" onSubmit="return ValidateForm()">
<fieldset>
<legend>Please enter Start Date and End Date</legend>
<div style="text-align: center; margin: 150px auto 100px auto;">
<label for="dateFrom">Start Date:</label>
<font color="#CC0000"><b>(dd/mm /yyyy)</b></font>
<input type="text" name="dateFrom" maxlength="25" size="25"
id="dateFrom" />
<img src = "../Images/calendar_1.png" onclick="javascript:Calendar.setup(inputField,ifFormat,button) style="cursor: pointer" />
</div>
<div style="text-align: center; margin: 150px auto 100px auto;">
<label for="dateTo">End Date:</label>
<font color="#CC0000"><b>(dd/mm/yyyy)</b></font>
<input type="text" name="dateTo" maxlength="25" size="25"
id="dateTo" />
</div>
<div>
<input type="submit" value="Generate Report" align="center" />
</div>
</form>
</div>
<script language="Javascript" >
var dtCh= "/";
var minYear=1900;
var maxYear=2500;
function isInteger(s){
var i;
for (i = 0; i < s.length; i++){
// Checking that the current character is number.
var c = s.charAt(i);
if (((c < "0") || (c > "9")))
return false;
}
// All characters are numbers.
return true;
}
function stripCharsInBag(s, bag){
var i;
var returnString = "";
// Search through string's characters one by one.
// If character is not in bag, append to returnString.
for (i = 0; i < s.length; i++){
var c = s.charAt(i);
if (bag.indexOf(c) == -1) returnString += c;
}
return returnString;
}
function daysInFebruary (year){
return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
for (var i = 1; i <= n; i++) {
this[i] = 31
if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
if (i==2) {this[i] = 29}
}
return this
}
function isDate(dtStr){
var daysInMonth = DaysArray(12)
var pos1=dtStr.indexOf(dtCh)
var pos2=dtStr.indexOf(dtCh,pos1+1)
var strDay=dtStr.substring(0,pos1)
var strMonth=dtStr.substring(pos1+1,pos2)
var strYear=dtStr.substring(pos2+1)
strYr = strYear
if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
for (var i = 1; i <= 3; i++) {
if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
}
month=parseInt(strMonth)
day=parseInt(strDay)
year=parseInt(strYr)
if (pos1==-1 || pos2==-1){
alert("The date format should be : dd/mm/yyyy");
return false;
}
if (strMonth.length<1 || month<1 || month>12){
alert("Please enter a valid month");
return false;
}
if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
alert("Please enter a valid day");
return false;
}
if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear);
return false;
}
if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))== false){
alert("Please enter a valid date");
return false;
}
return true;
}
function ValidateForm(){
var dt1=document.date.dateFrom
var dt2=document.date.dateTo
if (!isDate(dt1.value)){
dt1.value='';
dt1.focus();
return false;
}
if(!isDate(dt2.value)){
dt2.value='';
dt2.focus();
return false;
}
return true
}
}
</script>
</body>
</html>
I want changes in code to be done as:
The code should initialises the calendar object and links an image to a text field (using their IDs) to respond to a click.
Calendar.setup(
{
inputField : "dateFrom", // ID of the input field
ifFormat : "%d/%m/%Y", // the date format
button : "imgCal" // ID of the calendar image
}
);
should I really need to create a calendar object if so, can I know where. Also, where should I place the Calendar.setup code in my jsp page?
Can someone please help me sort out this issue...
Quick suggestion: Have you tried looking into this page.
Easy to implement and you can see the demo as well.
http://www.kelvinluck.com/assets/jquery/datePicker/v2/demo/
**
Now, Looking into your code; can you please flick the calender.setup(foo1, foo2...) function implementation? (Is this your customized library?)
Thanks,
i am trying to validate date with **YYYY\MM\DD of format using HTML and Javascript
Hope its Help you...
try to yourself...
< script type = "text/javascript" >
function valdate() {
var regdate = /^(19[0-9][0-9]|20[0-9][0-9])\/(0[1-9]|1[012])\/(0[1-9]|[12][0-9]|3[01])$/;
if (form1.txtdate.value.match(regdate)) {
return true;
} else {
alert("! please Enter the Date in this Format 'YYYY/MM/DD'");
form1.txtdate.value = "";
form1.txtdate.focus();
return false;
}
} < /script>
<from="form1" method="post" action="">
<input name="txtdate" type="text" onblur="valdate()" maxlength="10" required />
</form>
if helpful so make voting....

Show error message in a tool tip

I've a user registration form and I want to show the password rules in small tool tip along with the validation message like invalid password or valid password.My password rule is it contains 7 letters, 1 digit and 1 upper case letter etc.
Currently I've both of these but showing it in two different tool tip how can I merge two and show it in a single one.
<html>
<head>
<script src="http://cdn.jquerytools.org/1.2.6/full/jquery.tools.min.js"></script>
<title>Test</title>
</head>
<script>
function validatePassword(obj) {
//rule contains 7 chars and upper case and lower case and digit
var password = obj.value;
var numLowers = 0;
var numCaps = 0;
var numDigits = 0;
var valid = true;
if(password.length > 7) {
for(i = 0; i < password.length; i++) {
var charCode = password.charCodeAt(i);
if(charCode >= 48 && charCode <= 58 )
numDigits++;
else if(charCode >= 65 && charCode <= 90 )
numCaps++;
else if(charCode >= 97 && charCode <= 122 )
numLowers++;
}
if(numDigits < 1 || numCaps < 1 )
valid = false;
}
else {
valid = false;
}
if(!valid){
document.getElementById("password-error").style.display="block";
}
else {
document.getElementById("password-error").style.display="none";
}
}
</script>
<body>
<div>
<form id="test" action ="#">
<div id="password-container">
<input type="text" id= "password" name="password" size="30" onKeyUp="validatePassword(this)" title=" Password contains 7 -20characters <br/> and upper case and digits." />
</div>
<div id="password-error" class="error" style="display:none;">Invalid Password</div>
</form>
</div>
</body>
</html>
$("#test :input").tooltip({
// place tooltip on the right edge
position: "center right",
// a little tweaking of the position
offset: [-2, 10],
// use the built-in fadeIn/fadeOut effect
effect: "fade",
// custom opacity setting
opacity: 0.7
});
You can see a working example here
http://jsfiddle.net/ddrYp/6/
Here's a solution, you won't need to use both the tooltip and password error div.
http://jsfiddle.net/ddrYp/12/
But you may run into problems with this in the future because the tooltips are not uniquely identified. I'm not familiar with the plugin, but if you could add an individual ID to each tooltip, that's fix it for you. Once you do that, you could reference the tooltips by using their ID instead of $(".tooltip")... if you expand this to have multiple inputs when you do $(".tooltip").append(/*something*/) or $(".tooltip").HTML(/*something*/) you're going to modify every tooltip.. which may not matter, because only one is visible at a time... but it's still an inefficiency issue and a bit of a bug
Here's the example of the ebay password verification example that you were looking for:
http://jsfiddle.net/cFrpz/7/
Try this http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/
Here you go :
<html>
<head>
<script src="http://cdn.jquerytools.org/1.2.6/full/jquery.tools.min.js"></script>
<title>Test</title>
</head>
<script>
function validatePassword(obj) {
//rule contains 7 chars and upper case and lower case and digit
var password = obj.value;
var numLowers = 0;
var numCaps = 0;
var numDigits = 0;
var valid = true;
if(password.length > 7) {
for(i = 0; i < password.length; i++) {
var charCode = password.charCodeAt(i);
if(charCode >= 48 && charCode <= 58 )
numDigits++;
else if(charCode >= 65 && charCode <= 90 )
numCaps++;
else if(charCode >= 97 && charCode <= 122 )
numLowers++;
}
if(numDigits < 1 || numCaps < 1 )
valid = false;
}
else {
valid = false;
}
if(!valid){
$(".tooltip").append($("#password-error"));
document.getElementById("password-error").style.display="block";
}
else {
document.getElementById("password-error").style.display="none";
}
}
</script>
<body>
<div>
<form id="test" action ="#">
<div id="password-container">
<input type="text" id= "password" name="password" size="30" onKeyUp="validatePassword(this)" title=" Password contains 7 -20characters <br/> and upper case and digits." />
</div>
<div id="password-error" class="error" style="display:none;">Invalid Password</div>
</form>
</div>
</body>
http://jsfiddle.net/ddrYp/9/
I haven't tested this but it should be fine. From your working example, replace this:
if(!valid){
document.getElementById("password-error").style.display="block";
}
else {
document.getElementById("password-error").style.display="none";
}
with this:
$tooltip = $(".tooltip");
if(!valid && $tooltip.find("div.error").length < 1){
$tooltip.append("<div class='error'>"+$("#password-error").html()+"</div>");
}
else if(valid) {
$tooltip.find(".error").remove();
}

Categories

Resources