Javascript Validation for a Complex Password [duplicate] - javascript

This question already has answers here:
Password Strength Meter [closed]
(3 answers)
Closed 9 years ago.
I'm creating a Create Account page and I'm trying to verify that the password they are creating follows the proper format.
The password format needs to be:
Minimum of:
15 characters
2 UPPER
2 lower
2 Numbers
2 Special
I've searched and have only been able to find a validation script that checks for 1 of each character, which I am currently using. I'm also using a function to confirm the password and confrim password fields match on key up, and a separate function to do the same on submit. Validating that they match on submit is not working either.
Here's what I have so far:
<script>
var anUpperCase = /[A-Z]/;
var aLowerCase = /[a-z]/;
var aNumber = /[0-9]/;
var aSpecial = /[!|#|#|$|%|^|&|*|(|)|-|_]/;
function testpasswd(form, ctrl, value)
{
if (value.length < 15 || value.search(anUpperCase) == -1 ||
value.search (aLowerCase) == -1 || value.search (aNumber) == -1 || value.search (aSpecial) == -1)
{
document.getElementById("pw").innerHTML="Invalid Password";
}
else
{
location.href = "submit.cfm";
}
}
function checkpasswds()
{
theForm = document.getElementById ( 'reg' ) ;
confm = document.getElementById ( 'confirm') ;
if (theForm.passwd2.value != '' && theForm.passwd1.value != '')
{
if (theForm.passwd1.value != theForm.passwd2.value)
{
confm.style.background = "url('images/wrong.png')" ;
confm.style.backgroundRepeat = "no-repeat" ;
confm.style.backgroundPosition = "right" ;
}
else
{
confm.style.background = "url('images/correct.png')" ;
confm.style.backgroundRepeat = "no-repeat" ;
confm.style.backgroundPosition = "right" ;
}
}
}
function cnfmpasswd(form, ctrl, value)
{
theForm = document.getElementById ( 'reg') ;
if (theForm.passwd2.value != '' && theForm.passwd1.value != '')
{
if (theForm.passwd1.value != theForm.passwd2.value)
{
return (false);
}
else
{
return (true);
}
}
}
function submitForm()
{
document.forms['reg'].submit;
testpasswd('reg','passwd1',document.getElementById('passwd1').value);
cnfmpasswd('reg','passwd2',document.getElementById('passwd2').value);
}
</script>
<cfform action="submit.cfm" method="post" name="reg" id="reg" format="html">
<table width="947" border="0">
<tr>
<td width="180" align="right"><p style="color:#EB0000; font-size:14px" align="center" id="pw"></p></td>
<td width="118" align="right">
Password:
</td>
<td width="635">
<cfinput
name="passwd1"
title="Must contain at least 2 of each of the following: UPPERCASE, lowercase, numeric, and special characters"
type="password"
required="yes"
onKeyUp="checkpasswds();"
/>
(min 15 characters with 2 UPPER, 2 lower, 2 numeric, and 2 special)
</td>
</tr>
<tr>
<td id="confirm" align="right"></td>
<td align="right">
Confirm Password:
</td>
<td>
<cfinput
name="passwd2"
type="password"
required="yes"
onKeyUp="checkpasswds();"
/>
</td>
</tr>
<tr>
<td> </td>
<td> </td>
<td>
<cfinput name="submit"
type="button"
value="Submit"
class="button"
onClick="submitForm()"
/>
</td>
</tr>
</table>
I'm a little new with javascript. Details will be greatly appreciated. I hope someone can help! Thanks!
I'm not looking for a strength meter or on keyup validation. I simply want to validate the password on submit.

This should do it:
var password = "TEstpass1aaaaaaa$$";
console.log(isOkPass(password));
function isOkPass(p){
var anUpperCase = /[A-Z]/;
var aLowerCase = /[a-z]/;
var aNumber = /[0-9]/;
var aSpecial = /[!|#|#|$|%|^|&|*|(|)|-|_]/;
var obj = {};
obj.result = true;
if(p.length < 15){
obj.result=false;
obj.error="Not long enough!"
return obj;
}
var numUpper = 0;
var numLower = 0;
var numNums = 0;
var numSpecials = 0;
for(var i=0; i<p.length; i++){
if(anUpperCase.test(p[i]))
numUpper++;
else if(aLowerCase.test(p[i]))
numLower++;
else if(aNumber.test(p[i]))
numNums++;
else if(aSpecial.test(p[i]))
numSpecials++;
}
if(numUpper < 2 || numLower < 2 || numNums < 2 || numSpecials <2){
obj.result=false;
obj.error="Wrong Format!";
return obj;
}
return obj;
}

Related

Get checkbox values with different class name in the same div id - jquery mvc

I am trying to get the values of checkboxes which are in the same divid but have different class name.
<tr>
<td colspan="4" align="center">
<div id="divEntities" style="width:100%;height:150px;overflow-y:scroll;align:center;">
<table cellspacing="2" cellpadding="2" width="95%" align="center" border="1">
#{
var i = 0;
while (i < Model.CompanyMaster.Count)
{
<tr>
<td style="width:50%" hidden="hidden"><input type="checkbox" class="EntityCheck" id="chkCompanyId" /> #Model.CompanyMaster[i].COMPANYID</td>
#if ((i + 1) < Model.CompanyMaster.Count)
{
<td><input type="checkbox" class="EntityCheck" /> #Model.CompanyMaster[i + 1].COMPANY_NAME</td>
<td><input type="checkbox" class="CurrentYear" /> #DateTime.Now.Year </td>
<td><input type="checkbox" class="PreviousYear" /> #DateTime.Now.AddYears(-1).Year </td>
<td><input type="checkbox" class="LastYear" /> #DateTime.Now.AddYears(-2).Year </td>
}
else
{
<td></td>
}
</tr>
i = i + 1;
}
}
</table>
</div>
</td>
</tr>
With above code, I am able to populate data in a table with multiple checkboxes, but unable to get the value of the checkbox where the class name is something other than EntityCheck. Below is my jQuery function:
function GetSelectedEntities() {
var entities = "";
$("#divEntities").find('td').each(function (i, el) {
var checkbox = $(this).find('input.EntityCheck');
//var check1 = $(this).find('CurrentYear');
//var check2 = $(this).find('PreviousYear');
//var check3 = $(this).find('LastYear');
var check1 = $('.CurrentYear').val();
var check2 = $('.PreviousYear').val();
var check3 = $('.LastYear').val();
if (checkbox != undefined && $(checkbox).length > 0 && $(checkbox).prop('checked') == true) {
var EntityData = jQuery.trim($(this).text());
if (entities == "") {
entities = EntityData;
}
else {
entities = entities + "|" + EntityData;
}
}
});
return entities;
}
jQuery function is invoked on a button click event:
<button style="font:normal 9pt Arial;height:30px;width:100px;border-radius:5px; border:none; background-color:royalblue; color:white" id="btnAdd" onclick="GetSelectedEntities(event);">
Add
</button>
I tried by giving the same class name to all the checkboxes but the problem was that I was able to get the values of the year checkbox, even if the CompanyName was not selected. I need the year values only if the CompanyName checkbox is checked and it's corresponding years. I also tried by giving the id='' to the year checkbox, but could not get the values.
I am unable to figure where I am going wrong. What is that I need to change in my jQuery to get the expected result?
Something like this would work:
$('#btnAdd').on('click', function(){
var checked = $('table').find('input:checked');
checked.each(function(){
alert($(this).closest('td').text());
//do your stuff here..
});
});
Se working fiddle: https://jsfiddle.net/c8n4rLjy/
I had to make changes to get the desired solution. Please find the solution below:
<tr>
<td colspan="4" align="center">
<div id="divEntities" style="width:100%;height:150px;overflow-y:scroll;align:center;">
<table cellspacing="2" cellpadding="2" width="95%" align="center" border="1">
#{
var i = 0;
while (i < Model.CompanyMaster.Count)
{
<tr>
<td style="width:50%" hidden="hidden"><input type="checkbox" class="EntityCheck" id="chkCompanyId" /> #Model.CompanyMaster[i].COMPANYID</td>
#if ((i + 1) < Model.CompanyMaster.Count)
{
<td><input type="checkbox" class="EntityCheck" /> #Model.CompanyMaster[i + 1].COMPANY_NAME</td>
<td><input type="checkbox" class="chkYear" /> #DateTime.Now.Year </td>
<td><input type="checkbox" class="chkYear" /> #DateTime.Now.AddYears(-1).Year </td>
<td><input type="checkbox" class="chkYear" /> #DateTime.Now.AddYears(-2).Year </td>
}
else
{
<td></td>
}
</tr>
i = i + 1;
}
}
</table>
</div>
</td>
</tr>
jQuery:
function GetSelectedEntities() {
var entities = "";
var CompanySelected = false;
var counter = 0;
$("#divEntities").find('td').each(function (i, el) {
counter = counter + 1
var checkbox = $(this).find('input.EntityCheck');
var checkboxyear = $(this).find('input.chkYear');
if (counter == 2) {
if (checkbox != undefined) {
if ($(checkbox).prop('checked') == true) {
CompanySelected = true;
var EntityData = jQuery.trim($(this).text());
if (entities == "") {
entities = EntityData;
}
else {
entities = entities + "-" + EntityData;
}
}
else {
CompanySelected = false;
}
}
}
if (counter > 2) {
if (CompanySelected == true) {
if (checkboxyear != undefined) {
if ($(checkboxyear).prop('checked') == true) {
var EntityData = jQuery.trim($(this).text());
entities = entities + "|" + EntityData;
}
}
}
}
if(counter == 5)
{
counter = 0;
}
});
return entities;
}

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.

More efficient way to enable/disable multiple input fields JS

PROBLEM:
I have form which submits list of fields. My form includes 2 'overwrite' fields:
counter - how many items to be submitted
field overwrite - if filled it suppose to overwrite all inputs in table with the same value
finally I have 5 field inputs (field_1, field_2, field_3, field_4 and field_5).
What I am trying to do is:
Counter - when filled it will disable field_ with number lower than value in counter, eg. when counter = 3, inputs field_4 and field_5 will get disabled.
field_0 - when empty, I would like user to be able to fill anything in table. When populated, I would like field_0 to be copied over to all cells in table.
WHAT I HAVE DONE:
I currently have extremely inefficient working code. I have complicated 'if' statement which checks counter and field_0 individually for every single of items (field_1 - field_5) one by one and sets them to enable/disable or copies over field_0 value. I also have 'clearFieldClass' function which clears all items with class 'field' when field_0 is being changed. While it works for 5 fields and one field type final version of the page will have 200 fields x 10 different classes. I am trying to avoid having 2000 lines of code doing basically he same thing.
function clearFieldClass() {
var elements = [] ;
elements = document.getElementsByClassName("field");
for(var i=0; i<elements.length ; i++){
elements[i].value = "" ;
}
}
<form action="https://www.tobesubmitted.to.com?" onchange="
if (counter.value > 0 && field_0.value == '') {document.getElementById('field_1').disabled = false;} else if (counter.value > 0 && field_0.value !== '') {field_1.value = field_0.value, document.getElementById('field_1').disabled = false;} else {document.getElementById('field_1').disabled = true; field_1.value = ''};
if (counter.value > 1 && field_0.value == '') {document.getElementById('field_2').disabled = false;} else if (counter.value > 1 && field_0.value !== '') {field_2.value = field_0.value, document.getElementById('field_2').disabled = false;} else {document.getElementById('field_2').disabled = true; field_2.value = ''};
if (counter.value > 2 && field_0.value == '') {document.getElementById('field_3').disabled = false;} else if (counter.value > 2 && field_0.value !== '') {field_3.value = field_0.value, document.getElementById('field_3').disabled = false;} else {document.getElementById('field_3').disabled = true; field_3.value = ''};
if (counter.value > 3 && field_0.value == '') {document.getElementById('field_4').disabled = false;} else if (counter.value > 3 && field_0.value !== '') {field_4.value = field_0.value, document.getElementById('field_4').disabled = false;} else {document.getElementById('field_4').disabled = true; field_4.value = ''};
if (counter.value > 4 && field_0.value == '') {document.getElementById('field_5').disabled = false;} else if (counter.value > 4 && field_0.value !== '') {field_5.value = field_0.value, document.getElementById('field_5').disabled = false;} else {document.getElementById('field_5').disabled = true; field_5.value = ''};
">
<table border="0">
<tr>
<th align="left">Overwrites</th>
<th></th>
</tr>
<tr>
<td><label>Counter </label></td>
<td><input required type="text" id="counter" name="counter" placeholder="Max 50"></input></td>
</tr>
<tr>
<td><label>Overwrite field: </label></td>
<td><input required type="text" id="field_0" name="field_0" placeholder="Field" onchange="clearFieldClass()"></input></td>
</tr>
</table><br><br>
<table>
<tr align="left">
<th>Field</th>
</tr>
<tr>
<td><input required type="text" class='field' id="field_1"></td>
</tr>
<tr>
<td><input required type="text" class='field' id="field_2"></td>
</tr>
<tr>
<td><input required type="text" class='field' id="field_3"></td>
</tr>
<tr>
<td><input required type="text" class='field' id="field_4"></td>
</tr>
<tr>
<td><input required type="text" class='field' id="field_5"></td>
</tr>
</table>
<input type="submit" value="Submit form"></input>
Remove onchange attribute from your html and use the following code:
document.querySelector('form').addEventListener('change', () => {
document.querySelectorAll('.field').forEach((_el, index) => {
if(!isNaN(+counter.value) && +counter.value != 0 && index + 1 > +counter.value){
_el.disabled = 'disabled';
_el.value = '';
console.log('in')
}
else{
_el.removeAttribute('disabled');
_el.value = field_0.value;
}
});
})

Focus function in JavaScript

HTML Code:
<html>
<head>
<title>Registration</title>
<meta charset="utf-8">
<link href="home.css" rel="stylesheet" type="text/css"/>
<link href="booking.css" rel="stylesheet" type="text/css"/>
<script src="val_registration.js" type="text/javascript"></script>
<link rel="stylesheet" href="jquery.css">
<script src="jquery01.js" type="text/javascript"></script>
<script src="jquery02.js" type="text/javascript"></script>
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
<script language="JavaScript1.2">
var howOften = 5; //number often in seconds to rotate
var current = 0; //start the counter at 0
var ns6 = document.getElementById&&!document.all; //detect netscape 6
// place your images, text, etc in the array elements here
var items = new Array();
items[0]="<a href='link.htm'><img alt='photo01' src='photo01.jpg' height='237' width='750' border-style='inset' border-weight:'10px' /></a>"; //a linked image
items[1]="<a href='link.htm'><img alt='photo02' src='photo02.jpg' height='237' width='750' border-style='inset' border-weight:'10px'/></a>"; //a linked image
items[2]="<a href='link.htm'><img alt='photo03' src='photo03.jpg' height='237' width='750' border-style='inset' border-weight:'10px'/></a>"; //a linked image
items[3]="<a href='link.htm'><img alt='photo04' src='photo04.jpg' height='237' width='750' border-style='inset' border-weight:'10px'/></a>"; //a linked image
items[4]="<a href='link.htm'><img alt='photo05' src='photo05.jpg' height='237' width='750' border-style='inset' border-weight:'10px'/></a>"; //a linked image
function rotater() {
document.getElementById("placeholder").innerHTML = items[current];
current = (current==items.length-1) ? 0 : current + 1;
setTimeout("rotater()",howOften*1000);
}
function rotater() {
if(document.layers) {
document.placeholderlayer.document.write(items[current]);
document.placeholderlayer.document.close();
}
if(ns6)document.getElementById("placeholderdiv").innerHTML=items[current]
if(document.all)
placeholderdiv.innerHTML=items[current];
current = (current==items.length-1) ? 0 : current + 1; //increment or reset
setTimeout("rotater()",howOften*1000);
}
window.onload=rotater;
</script>
</head>
<body>
<div id="login" name="login">
&nbsp Login&nbsp&nbsp<b><b>|</b></b>
&nbspNew user?&nbsp&nbsp
</div>
<img src="logo.jpg" alt="logo" id="logo" width="500" height="100" usemap="#logomap"/></br>
<map id="logomap" name="logomap">
<area shape="rect" coords="0,0,743,146" href="home.htm" alt="home"/>
<area shape="default" coords"0,0,743,146" href="home.htm" alt="home"/>
</map></br>
<div id="placeholderdiv"></div><br/>
<div id="mlink" >
Home
About Us
Promotion
Contact Us
FAQs
</div><br/>
<div id="opac">
<h1> Registration </h1>
<hr/>
<form action="success(registration_page).html" method="post" id="myform" onsubmit="return val_registration ()">
<table rules="none" cellpadding="10px" cellspacing="10px">
<tr>
<td><label for="Username">Username(No case sensitive):<span id="imp">*</span></label></td><td><input type="text" id="Username" tabindex="1"/>
<br/><span class="eg"> eg:ZerOGravitY</span></td>
</tr>
<tr>
<td><label for="Password">Password(Must more than<br/> 8 characters):<span id="imp">*</span></label></td><td><input type="text" id="Password" tabindex="2"/>
<br/><span class="eg"> eg:567834gravity</span></td></td>
</tr>
<tr>
<td><label for="Retype_password">Retype password:<span id="imp">*</span></label></td><td><input type="text" id="Retype_password" tabindex="3"/>
<br/><span class="eg"> eg:567834gravity</span></td></td>
</tr>
<tr>
<td><label for="First_name">First name:<span id="imp">*</span></label></td><td><input type="text" id="First_name" tabindex="4"/>
<br/><span class="eg"> eg:Loh</span></td></td>
</tr>
<tr>
<td><label for="Last_name">Last name:<span id="imp">*</span></label></td><td><input type="text" id="Last_name" tabindex="5"/>
<br/><span class="eg"> eg:Le You</span></td></td>
</tr>
<tr>
<td><label for="ID_number">ID number (Please omit '-') :<span id="imp">*</span></label></td><td><input type="text" id="ID_number" maxlength="12" tabindex="6"/>
<br/><span class="eg"> eg:940731140991</span></td></td>
</tr>
<tr>
<td><label for="datepicker">DOB:<span id="imp">*</span></label></td>
<td><input type="text" id="datepicker" tabindex="7"/></td>
</tr>
<tr>
<td>Mobile number:<span id="imp">*</span></td>
<td colspan="3">
<select tabindex="8">
<optgroup label="Prefix">
<option value="010">010</option>
<option value="012">012</option>
<option value="013">013</option>
<option value="016">016</option>
<option value="017">017</option>
<option value="018">018</option>
<option value="019">019</option>
</optgroup>
</select>
<input type="text" id="Mobile_number" tabindex="9"/>
<input type="text" class="err" id="err_Mobile_number" readonly="readonly"/>
<br/><span class="eg">
eg:2345678 or 23456789</span>
</td>
</tr>
<tr>
<td><label for="E_mail">E-mail:<span id="imp">*</span></label></td>
<td><input type="text" id="E_mail" tabindex="10"/>
<br/><span class="eg"> eg:abc123#hotmail.com</span></td></td>
</tr>
<tr>
<td colspan="4"><input type="submit" value="Confirm" id="confirm2" tabindex="11" />
<input type="reset" value="Cancel" id="cancel2" tabindex="12"/></td>
</tr>
<tr>
<td>Notes: <span id="imp">*</span> indicates the column that must be filled</td>
</tr>
</table>
</form>
</div>
<hr/>
<b><i id="copyright">Copyrighted : © 2014 I ♥ Travels agency. </i></b>
<b><address id="address"> Address : I love agency, Taman Setapak, Jalan Genting Klang, 53300 Kuala Lumpur </address></b>
</body>
</html>
This is my JavaScript code (for form validation):
function val_registration ()
{
var val_Username = document.getElementById("Username").value;
var string_Username = /^[a-zA-Z0-9]{1,}$/;
var err = "";
if (val_Username == null || val_Username == "" || !string_Username.test(val_Username))
{
err += "\u2022Username cannot be blank/Username can contain\n alphabets or numbers only.\n";
document.getElementById("Username").focus();
}
var val_Password = document.getElementById("Password").value;
var string_Password = /^[a-zA-Z0-9]{9,}$/;
if (val_Password == null || val_Password == "" || !string_Password.test(val_Password))
{
err += "\u2022Password cannot be blank/Password can contain\n alphabets or numbers only and it must contain at \n least 9 characters.\n";
document.getElementById("Password").focus();
}
var val_Retype_password = document.getElementById("Retype_password").value;
if (val_Retype_password == null || val_Retype_password == "" || val_Retype_password != val_Password)
{
err += "\u2022Retype password cannot be blank/Retype password\n must same with password typed.\n";
document.getElementById("Retype_password").focus();
}
var val_First_name = document.getElementById("First_name").value;
var string_First_name = /^[a-zA-Z]{1,}$/;
if (val_First_name == null || val_First_name == "" || !string_First_name.test(val_First_name))
{
err += "\u2022Firstname cannot be blank/Firstname can contain \u00A0alphabets only.\n";
document.getElementById("First_name").focus();
}
var val_Last_name = document.getElementById("Last_name").value;
var string_Last_name = /^[ a-zA-Z#'\-_()\.,]{1,}$/;
if (val_Last_name == null || val_Last_name == "" || !string_Last_name.test(val_Last_name))
{
err += "\u2022Lastname cannot be blank/Lastname can contain\n alphabets or special symbols(# ' - _ ( ).,) only.\n";
document.getElementById("Last_name").focus();
}
var val_ID_number = document.getElementById("ID_number").value;
var string_ID_number = /^[0-9]{12}$/;
if (val_ID_number == null || val_ID_number == "" || !string_ID_number.test(val_ID_number))
{
err += "\u2022Id number cannot be blank/Id number can contain\n excatly 12 numbers only.\n";
document.getElementById("ID_number").focus();
}
var val_datepicker = document.getElementById("datepicker").value;
if (val_datepicker == null || val_datepicker == "")
{
err += "\u2022DOB cannot be blank.\n";
document.getElementById("datepicker").focus();
}
var val_Mobile_number = document.getElementById("Mobile_number").value;
var string_Mobile_number = /^[0-9]{7,8}$/;
if (val_Mobile_number == null || val_Mobile_number == "" || !string_Mobile_number.test(val_Mobile_number))
{
err += "\u2022Mobile number cannot be blank/Mobile number can\n \u00A0contain 7 or 8 numbers only.\n";
document.getElementById("Mobile_number").focus();
}
var val_E_mail = document.getElementById("E_mail").value;
var atpos = val_E_mail.indexOf("#");
var dotpos = val_E_mail.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2 >= val_E_mail.length)
{
err += "\u2022E-mail cannot be blank/E-mail format must follow\n \u00A0the example provided.\n";
document.getElementById("E_mail").focus();
}
if (err != null || err != "")
{
alert(err);
return false;
}
}
This works fine except for one thing:
When all fields are empty, an alert box pops up to indicate the error. However, after I click 'OK', it directly moves to the DOB field instead of
the username field.
When I click OK, I want it to validate and focus on the first element in the sequence which is not filled or is invalid.
For example: If both the username and password fields are empty and I click OK, the focus should go to the username field first.
you need to return false; after each validation check!
try this:
Edit1:
function val_registration()
{
var $invalidInput;
var val_Username = document.getElementById("Username").value;
var string_Username = /^[a-zA-Z0-9]{1,}$/;
var err = "";
if (val_Username == null || val_Username == "" || !string_Username.test(val_Username))
{
err += "\u2022Username cannot be blank/Username can contain\n alphabets or numbers only.\n";
var $input = document.getElementById("Username");
$invalidInput=$input;
}
var val_Password = document.getElementById("Password").value;
var string_Password = /^[a-zA-Z0-9]{9,}$/;
if (val_Password == null || val_Password == "" || !string_Password.test(val_Password))
{
err += "\u2022Password cannot be blank/Password can contain\n alphabets or numbers only and it must contain at \n least 9 characters.\n";
if($invalidInput==undefined){
var $input = document.getElementById("Password");
$invalidInput=$input;
}
}
var val_Retype_password = document.getElementById("Retype_password").value;
if (val_Retype_password == null || val_Retype_password == "" || val_Retype_password != val_Password)
{
err += "\u2022Retype password cannot be blank/Retype password\n must same with password typed.\n";
if($invalidInput==undefined){
var $input = document.getElementById("Retype_password");
$invalidInput=$input;
}
}
var val_First_name = document.getElementById("First_name").value;
var string_First_name = /^[a-zA-Z]{1,}$/;
if (val_First_name == null || val_First_name == "" || !string_First_name.test(val_First_name))
{
err += "\u2022Firstname cannot be blank/Firstname can contain \u00A0alphabets only.\n";
if($invalidInput==undefined){
var $input = document.getElementById("First_name");
$invalidInput=$input;
}
}
var val_Last_name = document.getElementById("Last_name").value;
var string_Last_name = /^[ a-zA-Z#'\-_()\.,]{1,}$/;
if (val_Last_name == null || val_Last_name == "" || !string_Last_name.test(val_Last_name))
{
err += "\u2022Lastname cannot be blank/Lastname can contain\n alphabets or special symbols(# ' - _ ( ).,) only.\n";
if($invalidInput==undefined){
var $input = document.getElementById("Last_name");
$invalidInput=$input;
}
}
var val_ID_number = document.getElementById("ID_number").value;
var string_ID_number = /^[0-9]{12}$/;
if (val_ID_number == null || val_ID_number == "" || !string_ID_number.test(val_ID_number))
{
err += "\u2022Id number cannot be blank/Id number can contain\n excatly 12 numbers only.\n";
if($invalidInput==undefined){
var $input = document.getElementById("ID_number");
$invalidInput=$input;
}
}
var val_datepicker = document.getElementById("datepicker").value;
if (val_datepicker == null || val_datepicker == "")
{
err += "\u2022DOB cannot be blank.\n";
if($invalidInput==undefined){
var $input = document.getElementById("datepicker");
$invalidInput=$input;
}
}
var val_Mobile_number = document.getElementById("Mobile_number").value;
var string_Mobile_number = /^[0-9]{7,8}$/;
if (val_Mobile_number == null || val_Mobile_number == "" || !string_Mobile_number.test(val_Mobile_number))
{
err += "\u2022Mobile number cannot be blank/Mobile number can\n \u00A0contain 7 or 8 numbers only.\n";
if($invalidInput==undefined){
var $input = document.getElementById("Mobile_number");
$invalidInput=$input;
}
}
var val_E_mail = document.getElementById("E_mail").value;
var atpos = val_E_mail.indexOf("#");
var dotpos = val_E_mail.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= val_E_mail.length)
{
err += "\u2022E-mail cannot be blank/E-mail format must follow\n \u00A0the example provided.\n";
if($invalidInput==undefined){
var $input = document.getElementById("E_mail");
$invalidInput=$input;
}
}
if (err != null || err != "")
{
$invalidInput.focus();
alert(err);
return false;
}
}
Why it was not working before:
your script was checking each element setting focus and adding error message as required for each element till the last element in the list. Focus state can only be active for a single element on the page at a time. Since the last erroneous element was receiving the focus every time for all the elements, it never stopped at first element.
What I did:
In updated script: I took a variable to store invalid element's reference. As soon the code finds an invalid element- it assigns it to variable $invalidElement. It does the same for every element. So this way $invalidElement always refere to first erroneous element at a time whereas errors get added to the error list every time.
In the end it checks if error is not null. It it is, focus to the first erroneous element and show the error message.
Simple as that!
Hope it helps!
Usually on HTML, the focus order of elements depends on tabindex attribute.
However, if you want to avoid the "natural" or the defined by tabindex order of your focusing, you can always use
yourObject.focus();
Just define the situation you want to control and the behaviour you need to apply when it happens.

placeholder works for text but not password box in IE/Firefox using this javascript

Js File
//Modified from http://www.beyondstandards.com/archives/input-placeholders/
function activatePlaceholders()
{
var detect = navigator.userAgent.toLowerCase();
if (detect.indexOf("safari") > 0) return false;
var inputs = document.getElementsByTagName("input");
for (var i=0;i<inputs.length;i++)
{
if (inputs[i].getAttribute("type") == "text")
{
var placeholder = inputs[i].getAttribute("placeholder");
if (placeholder.length > 0)
{
inputs[i].value = placeholder;
inputs[i].onclick = function()
{
if (this.value == this.getAttribute("placeholder"))
{
this.value = "";
}
return false;
}
inputs[i].onblur = function()
{
if (this.value.length < 1)
{
this.value = this.getAttribute("placeholder");
}
}
}
}
else if (inputs[i].getAttribute("type") == "password")
{
var placeholder = inputs[i].getAttribute("placeholder");
if (placeholder.length > 0)
{
inputs[i].value = placeholder;
inputs[i].onclick = function()
{
if (this.value == this.getAttribute("placeholder"))
{
this.value = "";
}
return false;
}
inputs[i].onblur = function()
{
if (this.value.length < 1)
{
this.value = this.getAttribute("placeholder");
}
}
}
}
}
}
window.onload = function()
{
activatePlaceholders();
}
Html part
<form name="input" action="login.php" method="post">
<table width="*" border="0">
<tr>
<td align="left"><input type="text" name="username" placeholder="Username" /> <input type="password" name="pass" placeholder="Password" /><input type="submit" value="Login" /></td>
</tr>
<tr>
<td colspan="2" align="right">Stay logged in: <input type="checkbox" name="remember" value="1"> Sign Up | Forgot Password </td>
</tr>
</table>
</form>
This works for the input box. Not working for the password box. It wants to star out the place holder text on the password. I want to users password to be started out but not the place holder. Not sure how to fix that so it works in IE and Firefox.
var passwords = document.getElementsByTagName("password");
Should be:
var passwords = document.getElementsByTagName("input");
As it's <input type="password"> not <password...>. However, I don't think that will help you in this case, because when you set the value of the password, all you'll see are the black dots/asterisks.

Categories

Resources