Form validation backwards compatible with earlier versions of IE - javascript

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

Related

document.getElementsByTagName is working but same functionality is not working with document.getElementById

I was trying to change the color of placeholder of input tag using Javascript. I am able to achieve that if I use document.getElementsByTagName, but if I am using document.getElementById then it's not working.
HTML:
<input name="txtfirstName" type="text" id="input" placeholder="First Name" />
<input type="button" name="Button1" value="Register" onclick="ChangePlaceHolderColor();" />
JavaScript (with document.getElementsByTagName):
function ChangePlaceHolderColor() {
var textBoxes = document.getElementsByTagName("input");
for (var i = 0; i < textBoxes.length; i++) {
if (textBoxes[i].type == "text") {
if (textBoxes[i].value == "") {
textBoxes[i].className += " Red";
}
}
}
}
JavaScript (with document.getElementById):
function ChangePlaceHolderColor() {
var textBoxes = document.getElementById("input");
for (var i = 0; i < textBoxes.length; i++) {
if (textBoxes[i].type == "text") {
if (textBoxes[i].value == "") {
textBoxes[i].className += " Red";
}
}
}
}
I am not able to figure why this is happening.
getElementById returns only 1 element, it is not an array
function ChangePlaceHolderColorx() {
var textBoxes = document.getElementsByTagName("input");
for (var i = 0; i < textBoxes.length; i++) {
if (textBoxes[i].type == "text") {
if (textBoxes[i].value == "") {
textBoxes[i].className += "Red";
}
}
}
}
function ChangePlaceHolderColor() {
var textBoxes = document.getElementById("input");
if (textBoxes.type == "text") {
if (textBoxes.value == "") {
textBoxes.className += "Red";
}
}
}
.Red{
color:red;
}
<input name="txtfirstName" type="text" id="input" placeholder="First Name" />
<input type="button" name="Button1" value="Register" onclick="ChangePlaceHolderColor();" />
You have to change function ChangePlaceHolderColor() to:
function ChangePlaceHolderColor() {
var textBoxes = document.getElementById("input");
if (textBoxes.type == "text") {
if (textBoxes.value == "") {
textBoxes.className += " Red";
}
}
}
this is because getElementByTagName() will return HTMLCollection which you can treat as an Array, but getElementById() will return only one element.
getElementsByTagName will always return an array of HTML elements, whereas getElementsById will always return a single HTML element.
function ChangePlaceHolderColor() {
//no loop because the return is one element.
var textBoxes = document.getElementById("input");
if (textBoxes.type == "text") {
if (textBoxes.value == "") {
textBoxes.className += " Red";
}
}
}
In HTML, element IDs must be unique on any given page.

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.

I have an issue to create dynamic fields with string count using Javascript OR Jquery

I have an issue to create dynamic fields with string count using JavaScript or jQuery.
Briefing
I want to create dynamic fields with the help of sting count, for example when I write some text on player textfield like this p1,p2,p3 they create three file fields on dynamicDiv or when I remove some text on player textfield like this p1,p2 in same time they create only two file fields that's all.
The whole scenario depend on keyup event
Code:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function commasperatedCount(){
var cs_count = $('#player').val();
var fields = cs_count.split(/,/);
var fieldsCount = fields.length;
for(var i=1;i<=fieldsCount;i++){
var element = document.createElement("input");
element.setAttribute("type", 'file');
element.setAttribute("value", '');
element.setAttribute("name", 'file_'+i);
var foo = document.getElementById("dynamicDiv");
foo.appendChild(element);
}
}
</script>
<form>
<label>CountPlayerData</label>
<input type="text" name="player" id="player" onkeyup="return commasperatedCount();" autocomplete="off" />
<div id="dynamicDiv"></div>
<input type="submit" />
</form>
var seed = false,
c = 0,
deleted = false;
$('#player').on('keyup', function(e) {
var val = this.value;
if ($.trim(this.value)) {
if (e.which == 188) {
seed = false;
}
if (e.which == 8 || e.which == 46) {
var commaCount = val.split(/,/g).length - 1;
if (commaCount < c - 1) {
deleted = true;
}
}
commasperatedCount();
} else {
c = 0;
deleted = false;
seed = false;
$('#dynamicDiv').empty();
}
});
function commasperatedCount() {
if (deleted) {
$('#dynamicDiv input:last').remove();
deleted = false;
c--;
return false;
}
if (!seed) {
c++;
var fields = '<input value="" type="file" name="file_' + c + '">';
$('#dynamicDiv').append(fields);
seed = true;
}
}​
DEMO
<script>
function create(playerList) {
try {
var player = playerList.split(/,/);
} catch(err) {
//
return false;
}
var str = "";
for(var i=0; i<player.length; i++) {
str += '<input type="file" id="player-' + i + '" name="players[]" />';
//you wont need id unless you are thinking of javascript validations here
}
if(playerList=="") {str="";} // just in case text field is empty ...
document.getElementById("dynamicDiv").innerHTML = str;
}
</script>
<input id="playerList" onKeyUp="create(this.value);" /><!-- change event can also be used here -->
<form>
<div id="dynamicDiv"></div>
</form>

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

Fast way to validate if all checkboxes are un-selected?

Is there a quick way or function that would tell me true/false if all check boxes are deselected? Without going through array? (with JS and HTML)
All my check boxes have the same name...
<form action="/cgi-bin/Lib.exe" method=POST name="checks" ID="Form2">
<input type=checkbox name="us" value="Joe" ID="Checkbox1">
<input type=checkbox name="us" value="Dan" ID="Checkbox2">
<input type=checkbox name="us" value="Sal" ID="Checkbox3">
</form>
jQuery would be a mass of unneeded bloat for a task this trivial. Consider using it if you are running it for other purposes, but all you need is something like this:
function AreAnyCheckboxesChecked () {
var checkboxes = document.forms.Form2.elements.us;
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
return true;
}
}
return false;
}
You have to loop through them. Even a library like jQuery will loop through them, just hide it from you.
var form = document.getElementById('Form2');
var inputs = form.getElementsByTagName('input');
var is_checked = false;
for(var x = 0; x < inputs.length; x++) {
if(inputs[x].type == 'checkbox' && inputs[x].name == 'us') {
is_checked = inputs[x].checked;
if(is_checked) break;
}
}
// is_checked will be boolean 'true' if any are checked at this point.
JavaScript:
var allischecked = (function(){
var o = document.getElementById("Form2").getElementsByTagName("input");
for(var i=0,l=o.length;i<l;i++){
o[i].type === "checkbox" && o[i].name === "us" && o[i].checked || return false;
}
return true;
})();
With jQuery:
var allischecked = ($("#Form2 input:checkbox:not(checked)").length === 0);
In summary, this snipped will return true if all are NOT checked. It bails out as soon as a checked one is found.
var a = document.getElementsByName("us");
for(var i=0; i<a.length; i++)
if(a[i].checked)
return false;
return true;
(did not test, but conceptually it is valid)
What do you mean by
Without going through array
?
You could just do
function check() {
var anyChecked = false;
var form = document.getElementById('Form2');
var checkboxes = form.getElementsByTagName('input');
for(var i=0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
anyChecked = true;
break;
}
}
alert("Checkboxes checked? " + anyChecked);
}
Working Demo
If you have a large amount of checkboxes that you don't want to loop through to test it might be more efficient to use this approach.
var checked = 0;
$("input[type=checkbox]").live("click", function() {
if($(this).attr("checked")) checked++;
else checked--;
}
Then you would be able to test like this.
if(checked === 0) {
doSomething();
}
The proper solution with jQuery attribute checked:
$checkboxes = $('#Form2 input:checkbox');
$checkboxes.on('click', checkboxes);
function checkboxes() {
var allChecked = $checkboxes.not(':checked').length == 0;
console.log(allChecked);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<form action="/cgi-bin/Lib.exe" method=POST name="checks" ID="Form2">
<input type=checkbox name="us1" value="Joe" ID="Checkbox1"><label>Joe</>
<input type=checkbox name="us2" value="Dan" ID="Checkbox2"><label>Dan</>
<input type=checkbox name="us3" value="Sal" ID="Checkbox3"><label>Sal</>
</form>
Even easier without loop
const toggleCheckboxes = checkbox => {
if(checkbox.checked){
return true
}else{
if(document.querySelectorAll(':checked').length === 0){
// All are unchecked
return false
}
}
}

Categories

Resources