date validation in javascript using .js files - javascript

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....

Related

Java Script Functions Don't work and How do i add my javascript file to html and get it to work

I have my javascript file and code done, called script.js and I've added it to my HTML file. I'm very new to this and I'm not sure if I'm doing it right. the functions don't seem to work either. I am very lost and would just like yo figure it out. thank you.
this is my javascript file called (script.js)
$(document).ready(function () {
//When add database, will pull total from database
var total = 30;
var totalTax = total * 0.8;
var totalShip = total * 0.3;
var totalAll = total + totalTax + totalShip;
document.getElementById("totalShop").innerHTML = total;
document.getElementById("totalTax").innerHTML = totalTax;
document.getElementById("shipping").innerHTML = totalShip;
document.getElementById("totalDue").innerHTML = totalAll;
});
function applyActiveCss(id) {
for (var i = 0; i < document.links.length; i++) {
if (document.links[i].id == id) {
document.links[i].className = 'active';
}
else {
document.links[i].className = 'links';
}
}
}
function validateCheckout() {
if (document.checkoutForm.cardNumber.value == "") {
alert("Please provide card number");
document.checkoutForm.cardNumber.focus();
return false;
}
if (document.checkoutForm.month.value == "" || isNaN(document.checkoutForm.month.value) ||
document.checkoutForm.month.value.length != 2) {
alert("Please provide your month");
document.checkoutForm.month.focus();
return false;
}
if (document.checkoutForm.year.value == "" || isNaN(document.checkoutForm.year.value) ||
document.checkoutForm.year.value.length != 4) {
alert("Please provide your month");
document.checkoutForm.year.focus();
return false;
}
return (true);
}
function validateUserInfo() {
if (document.userInfo.fullname.value == "") {
alert("Please provide full name");
document.checkoutForm.cardNumber.focus();
return false;
}
if (document.userInfo.email.value == "") {
alert("Please provide your Email!");
document.userInfo.email.focus();
return false;
}
var emailID = document.userInfo.email.value;
var atpos = emailID.indexOf("#");
var dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || (dotpos - atpos < 2)) {
alert("Please enter correct email ID")
document.userInfo.email.focus();
return false;
}
if (document.userInfo.zipcode.value == "" ||
isNaN(document.userInfo.zipcode.value) ||
document.userInfo.zipcode.value.length != 5) {
alert("Please provide a zip in the format 12345");
document.userInfo.zipcode.focus();
return false;
}
var phoneID = document.userInfo.phone.value;
var dashpos1 = phoneID.indexOf("-");
var dashpos2 = phoneID.lastIndexOf("-");
for (var i = 3; i < 7; i++) {
phoneID[i] = phoneID[i + 1];
}
for (var j = 6; j < 8; j++) {
phoneID[j] = phoneID[j + 2];
}
if (document.userInfo.phone.value == "" ||
document.userInfo.phone.value.length != 12
|| dashpos1 != 3 || dashpos2 != 7 || isNaN(phoneID)) {
alert("Please provide a phone number in the format 123-456-7890");
document.userInfo.phone.focus();
return false;
}
return (true);
}
and this is part of my HTML file called (userinfo.html)
¿<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Personal Information</title>
<link rel="stylesheet" type="text/css" href="StyleSheet1.css">
</head>
<body>
<script src="script.js"> </script>
<h1>User Information</h1>
<p>Please fill out the following information.</p>
<!--<form class="" action="submit.php" method="post">-->
<form action=".shipinfo.html" name="userInfo" onsubmit="return (validateUserInfo());">
<table>
<tbody>
<tr>
<td>
Full Name: <br>
<input type="text" maxlength="100" name="fullname" required>
</td>
<td>
Phone Number: <br>
<input type="number" minlength = "12" maxlength="12" name="phone"
placeholder="123-456-7890">
</td>
</tr>
<tr>
<td>
Address Line 1: <br>
<input type="text" maxlength="100" name="add1" required>
</td>
<td>
Address Line 2: <br>
<input type="text" maxlength="100" name="add2">
</td>
</tr>
<tr>
<td>
City: <br>
<input type="text" maxlength="100" name="city" required>
</td>
I dont see the following jquery script in your file (so it does not read the document ready part and you do not see the 'document loaded' in your console.
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
Another error you are getting in the console is 'Cannot read property 'innerHTML' of null' for this:
document.getElementById("totalShip").innerHTML = total;
This happens when the element, in this case 'totalship', is not accessible or available in your webpage and as such its property cannot be read. Since you are accessing an id, can you provide your css file here?
In addition, where is the access to your database through these files (.userInfo, .checkoutForm etc.) are not accessible via your files as of now.

Jquery:Registration Number Validation on Keypress

I everyone I have a text-box
Number : <input type="text" name="Number" placeholder="MH03AH6414" id="txtRegNo" />
<span id="errmsg"></span>
The text-box must take value like the placeholder input(1st two character alphabet (a-z or A-Z) 2nd two character number (0-9) the 3rd two character alphabet (a-z or A-Z) and last four character number (0-9)
I have tried to do with key-press event and all but not formed properly
$("#txtRegNo").keypress(function (e) {
var dataarray = [];
var dInput = $(this).val();
for (var i = 0, charsLength = dInput.length; i < charsLength; i += 1) {
dataarray .push(dInput.substring(i, i + 1));
}
alert(dataarray);
alert(e.key);
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false
}
});
Please help me.
Thanks in advance
I tried of focusout which now works fine with me but I want to prevent from keyinput
Here is the jsfiddle solution
http://jsfiddle.net/ntywf/2470/
Try this out. Modified the function as per requirement
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
Number : <input type="text" name="Number" placeholder="MH03AH6414" id="txtRegNo" />
<span id="errmsg"></span>
<!-- end snippet -->
<script>
$("#txtRegNo").keyup(function (e) {
$("#errmsg").html('');
var validstr = '';
var dInput = $(this).val();
var numpattern = /^\d+$/;
var alphapattern = /^[a-zA-Z]+$/;
for (var i = 0; i < dInput.length;i++) {
if((i==2||i==3||i==6||i==7)){
if(numpattern.test(dInput[i])){
console.log('validnum'+dInput[i]);
validstr+= dInput[i];
}else{
$("#errmsg").html("Digits Only").show();
}
}
if((i==0||i==1||i==4||i==5)){
if(alphapattern.test(dInput[i])){
console.log('validword'+dInput[i]);
validstr+= dInput[i];
}else{
$("#errmsg").html("ALpahbets Only").show();
}
}
}
$(this).val(validstr);
return false;
});
</script>

auto tabbing on the first textbox isnt working

the following is code is used to create a credit card. My only promblem is that auto tabbing doesnt work for my textbox with the id of card.i have a external file for the auto tabbing and i have attached the code under the html code.Thanks in advance.
<head>
<title>Credit Card</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.min.js"></script>
<script src="jquery.autotab.js"></script>
<script src="Jstepper.js"></script>
</head>
</body oncopy="return false" oncut="return false" onpaste="return false">
<style>
#Month{
width: 20px;
}
#Year{
width: 40px;
}
#Cvc{
width: 30px;
}
</style>
<p>Payment:
Credit card<input type="radio" id='radio_1' name='payment' value="credit">
<div class="text1">
<form name="cardForm" method="post">
<p>Card number:<input type="text" name="FirstField" id='card' value=""
onKeyup="autotab(this,document.cardForm.SecondField)" maxlength=16 >
Expiration: Month:-<input type="text" name="SecondField" id='Month' value=""
onKeyup="autotab(this,document.cardForm.ThirdField)" maxlength=2 >
Year:-<input type="text" id='Year' name="ThirdField" value="" onKeyup="autotab(this, document.cardForm.FourthField)"maxlength=4></p>
3 digit CVC:-<input type="text" name="FourthField" id='Cvc' value="" maxlength=3></p>
</form>
</div>
</body>
<!--Jump when expiration number is typed-->
<!--month and year-->
<!--exp date has to greater than or equal to current date -->
<!--on every keypress check if the length is 16-->
<!--macthes-->
<!-- Import numeric from src folder-->
<script src="numeric.js"></script>
<script>
//autotab doesnt work for the first feild
//can still copy and paste text
$(document).ready(function () {
$(".text1").hide();
$("#radio_1").click(function () {
<!--passes card id to keypress function-->
$('#card').keypress();
//disable copy and paste
$('#card').bind();
$('#Month').keypress();
$('#Month').bind();
$('#Month').jStepper({minValue:0, maxValue:12});
$('#Year').keypress();
$('#Year').bind();
$('#Cvc').keypress();
$('#Cvc').bind();
$(".text1").show();
});
});
</script>
<html>
/*
Auto tabbing script- By JavaScriptKit.com
http://www.javascriptkit.com
This credit MUST stay intact for use
*/
function autotab(original,destination){
if (original.getAttribute&&original.value.length==original.getAttribute("maxlength"))
destination.focus()
}
my isnumeric file
$(this).keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
});
//check for the type of credit card and prints to console
$(this).keypress(function (e) {
var input = document.getElementById('card');
input.onkeyup = function() {
if(input.value.length == 16){
var str = input.value;
var VisaRegx = /^4[0-9]{6,}$/i;
var Visafound = str.match(VisaRegx);
if(Visafound != null){
console.log("Visa Found");
}
var MasterRegx = /^5[1-5][0-9]{5,}$/i;
var Masterfound = str.match(MasterRegx);
if(Masterfound != null){
console.log("Master Card Found");
}
var AmericanExpressRegx = /^3[47][0-9]{5,}$/i;
var AmericanExpressfound = str.match(AmericanExpressRegx);
if(AmericanExpressfound != null){
console.log("American Express Card Found");
}
//^(?:2131|1800|35[0-9]{3})[0-9]{3,}$
var DinersClubRegx = /^3(?:0[0-5]|[68][0-9])[0-9]{4,}$/i;
var DinersClubfound = str.match(DinersClubRegx);
if(DinersClubfound != null){
console.log("Diners Club Card Found");
}
var DiscoverRegx = /^6(?:011|5[0-9]{2})[0-9]{3,}$/i;
var Discoverfound = str.match(DiscoverRegx);
if(Discoverfound != null){
console.log("Discover Card Found");
}
var JcbRegx = /^(?:2131|1800|35[0-9]{3})[0-9]{3,}$/i;
var Jcbfound = str.match(JcbRegx);
if(Jcbfound != null){
console.log("Jcb Card Found");
}
}
}
});
//checks for credit card expiration
$(this).keypress(function (e) {
var Monthinput = document.getElementById('Month').value;
var Yearinput = document.getElementById('Year').value;
var today = new Date();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(Yearinput.length == 4){
if(yyyy > Yearinput){
console.log("The card is expired cause of the year");
}
}
if(Yearinput.length == 4 && Monthinput.length == 2){
if(yyyy == Yearinput && mm > Monthinput){
console.log("The card is expired cause of the current month");
}
}
});
//Disable copy and paste
$(this).bind("cut copy paste",function(e) {
e.preventDefault();
});

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

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