Form Validation with password match - javascript

I have two forms inside my body:
<body>
<form method=post name="signin">
<table>
<theader>Sign In</theader>
<tr>
<td>Email:</td>
<td>
<input type=text length=25 maxlength=25 name=em id=em />
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type=password length=15 maxlength=15 name=up id=up />
</td>
</tr>
<tr>
<td colspan=2>
<input type=button value="submit" />
</td>
</tr>
</table>
</form>
<br>
<br>
<br>
<br>
<form method=post name="register">
<table>
<theader>Don't have an account? Register, it's Free!</theader>
<tr>
<td>Email:</td>
<td>
<input type=text length=25 name=email id=email /><span id="nameerror"></span>
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type=password length=15 name=pass id=pass />
</td>
</tr>
<tr>
<td>Confirm Password:</td>
<td>
<input type=password length=15 name=cpass id=cpass /><span id="pwerror"></span>
</td>
</tr>
<tr>
<td>Account Type:</td>
<td>
<select id="seltype">
<option name=standard SELECTED>Standard</option>
<option name=admin>Administrator</option>
</td>
</tr>
<tr>
<td colspan=2>
<input type=button value="submit" onClick="JavaScript:validate();" />
</td>
</tr>
</table>
</form>
</body>
I would like to do the following:
For each form, validate to ensure it's filled in and also for the second form I want to validate that the two password matched. I have the following:
$( document ).ready(function() {
var t = document.getElementById("email").value;
var y = document.getElementById("seltype").value;
var k = document.getElementById("pass").value;
var j = document.getElementById("cpass").value;
$('#cpass').blur(function(){
if (k != j) {
document.getElementById("pwerror").innerHTML = "Password does not match";
}
else {
document.getElementById("pwerror").innerHTML = "Password matches";
}
});
});
function validate() {
if (t != null && y != null && k != null && j != null) {
}
if (t == "" || y == "" || k == "" || j == "") {
alert("fill in");
}
}

I preferred not to mix native JavaScript and validated using pure jQuery only. One of the benefits here is that the empty field check would work for any <form> since it's not tied to any particular form, input name or ids.
$( document ).ready(function() {
$( 'form' ).submit(function(event) {
var $form = $( this );
var checkPass = true;
$form.find( 'input' ).each(function( i, e) {
if (e.value.length === 0) {
event.preventDefault();
alert(e.name + " cannot be empty");
return (checkPass = false);
}
});
if( checkPass && $form.is( '[name="register"]' ) ) {
if( $form.find( '#pass').val() !== $form.find( '#cpass' ).val()) {
event.preventDefault();
alert( 'Passwords do not match.' );
}
}
});
});
Working Demo at JsFiddle.net

Basics:
If you want to check if a variable is not null, ideally, you should use !== & not !=.
If you want to check if a variable is "", ideally, you should use === and not ==.
Check out: http://www.w3schools.com/js/js_comparisons.asp
Use JSFiddle.net to give a better working example of your code WHICH can help others see a demo of your actual code.
Your code currently has lot of scope for optimization. Since its just a basic validation you are trying to achieve, why do you need to use jQuery? Why not just use JavaScript basic variable comparisons?
Google before you ask here. If its so straightforward, your question will get downvoted.
Alert is not the best way to notify the user to fill in. For example, your 'Password Matches' or 'Password Doesn't Match' div is a much better way to notify the user. Use Form Events to validate the form as the user is already filling in the details in the form!
Question responsibly by giving your exact problems and not just pasting the code! How would we know where you are facing a problem.
Variables work in Scope. Check the scope of variable before using them in different functions. For example, you define var t, y, k, j in first function and use it in second function - will throw up an error of undefined variable t.
From what information you provided, here's what I could help with:
HTML:
<form method=post name="signin">
<table>
<theader>Sign In</theader>
<tr>
<td>Email:</td>
<td>
<input type=text length=25 maxlength=25 name=em id=em />
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type=password length=15 maxlength=15 name=up id=up />
</td>
</tr>
<tr>
<td colspan=2>
<input type=button value="submit" onclick="javascript:validateSignin()" />
</td>
</tr>
</table>
</form>
<br>
<br>
<br>
<br>
<form method=post name="register">
<table>
<theader>Don't have an account? Register, it's Free!</theader>
<tr>
<td>Email:</td>
<td>
<input type=text length=25 name=email id=email /><span id="nameerror"></span>
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type=password length=15 name=pass id=pass />
</td>
</tr>
<tr>
<td>Confirm Password:</td>
<td>
<input type=password length=15 name=cpass id=cpass /><span id="pwerror"></span>
</td>
</tr>
<tr>
<td>Account Type:</td>
<td>
<select id="seltype">
<option name=standard SELECTED>Standard</option>
<option name=admin>Administrator</option>
</td>
</tr>
<tr>
<td colspan=2>
<input type=button value="submit" onClick="JavaScript:validateRegister();" />
</td>
</tr>
</table>
</form>
JS:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
<script type="text/javascript">
$(document).ready(function () {
$('#cpass').blur(function () {
if (k != j) {
document.getElementById("pwerror").innerHTML = "Password does not match";
} else {
document.getElementById("pwerror").innerHTML = "Password matches";
}
});
});
function validateRegister() {
var t = document.getElementById("email").value;
var y = document.getElementById("seltype").value;
var k = document.getElementById("pass").value;
var j = document.getElementById("cpass").value;
if (t !== null && y !== null && k !== null && j !== null) {}
if (t === "" || y === "" || k === "" || j === "") {
alert("fill in");
}
}
function validateSignin() {
var se= document.getElementById("em").value;
var sp= document.getElementById("up").value;
if (se !== null && sp !== null){ }
if (se === "" || sp === "") {
alert("fill in");
}
}
</script>
Hope it helps! :)

Related

javascript Validation Help a total newbie

I Cannot get the javascript to work! I need the Password and Re-Type Password fields, validate that both have values and that the user has entered the same password in both fields (i.e. password match) validate the password field must be more than 8 characters.I dont want to use the alert function instead, highlight the uncompleted fields with red background and a text message next to each uncompleted field (in red color) with the error message.
I have spent 3 days doing this!! any help appreciated.`
function validate() {
var fn =
document.getElementById("FName");
if (fn.value == "") {
{
document.getElementById("FName").style.borderColor = "red";
return false;
}
return true;
}
function validate() {
var sn =
document.getElementById("SName");
if (sn.value == "") {
document.getElementById("SName").style.borderColor = "red";
return false;
}
return true;
}
function validate() {
var un =
document.getElementById("UName");
if (un.value == "") {
document.getElementById("UName").style.borderColor = "red";
return false;
}
return true;
}
function checkPass() {
var pass = document.getElementById('pass');
var c_pass = document.getElementById(' c_pass')
var message = document.getElementById('confirmMessage');
var goodColor = "#66cc66";
var badColor = "#ff6666";
if (pass.value == c_pass.value) {
c_pass.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "Passwords Match!"
} else {
c_pass.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = "Passwords Do Not Match!"
}
return true;
}
}
<body>
<form action="Linkpage.html" id="myForm" method="post" name="myForm" onsubmit="return(validate())">
</form>
<br>
<table>
<tr>
<td align="center" colspan="2"><span style="font-size:50px; color:blue;">Registration form</span>
</td>
</tr>
<tr>
<td align="center" colspan="2">Welcome to our website
<br>please fill in <span style=" color:red;">all</span>
<b><ins>fields</ins></b>
</td>
</tr>
<tr>
<td>First Name</td>
<td>
<input autofocus="" id="FName" placeholder="Enter First name " type="text">
</td>
</tr>
<tr>
<td>Last Name</td>
<td>
<input id="SName" placeholder="Enter Last name " type="text">
</td>
</tr>
<tr>
<td>Username</td>
<td>
<input id="UName" placeholder="Enter username " type "text">
</td>
</tr>
<tr>
<td>Age</td>
<td>
<input id="Age" placeholder="Enter age" type="text">
</td>
</tr>
<tr>
<td>Password</td>
<td>
<input id="pass" placeholder="Enter password " type="password">
</td>
</tr>
<tr>
<td>Confirm Password</td>
<td>
<input name="confirm password" id="c_pass" placeholder="Re-type your password " type="password" onkeyup="checkPass(); return false;">
<span id="confirmMessage" class="confirmMessage"></span>
</td>
</tr>
<tr>
<td rowspan="2">Gender</td>
<td>
<input name="mGender" type="radio" value="Male">Male</td>
</tr>
<tr>
<td>
<input name="fGender" type="radio" value="Female">Female</td>
</tr>
<tr>
<td>Available</td>
<td>
<input id="checkbox" type="checkbox">
</td>
</tr>
<tr>
<td>Course</td>
<td>
<select>
<option value="Mobile App">
Mobile App
</option>
<option value="Cloud">
Cloud
</option>
<option value="Software Development">
Software Development
</option>
</select>
</td>
</tr>
<tr>
<td class="Comments">Comments</td>
<td>
<br>
<textarea cols="30" name="Comments" placeholder="Type your comments here." rows="6"></textarea>
</td>
</tr>
<tr>
<td align="center" colspan="4" align="center">
<input name="submit" onclick="return validate()" type="submit" value="Register" align="center" />
</td>
</tr>
</table>
</body>
A couple of things here...
Get rid of the table, tr and td. You open a form and then you close it. Add all of your input fields in the form.
Then don't add three functions all called validate. Which one do you suppose is going to be called?
Rather change them to
function validateFname()
function validateSname()
function validateUname()
then
Use === and !=== instead of == and !=.
I think when you start clearing up your JavaScript and your HTML, things will start to make more sense.
Did you try to debug your code using Chrome's debugger or similar?
Each time you write the validate() function, you're overwriting the previous instance of it.
I recommend instead of using the same function name 3 times, write 2 different functions - matches() and required(), each with a different purpose.
matches(field1, field2){
return field1 == field2;
}
required(field){
return field != false;
}
Then you can pass into those functions the various fields you're validating.
There are a lot of bugs in your code and this is normal as a beginner its great to see you trying. So what I have done is took a look at your javascript. I am not going to re-write you whole script but I have commented out the part you should take a look at and try and comment one part at a time to see where you problem is. But I did get your match password working for you by commenting out your other stuff. Just try this for now. Then remove comments line by line until it stops working again. This will tell you how to find the other error's in your script.
<script>
function checkPass(){
var passValue = document.getElementById('pass').value;
var c_passValue = document.getElementById('c_pass').value;
var c_passID = document.getElementById('c_pass');
var message = document.getElementById('confirmMessage');
var goodColor = "#66cc66";
var badColor = "#ff6666";
if(passValue == c_passValue) {
c_passID.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "Passwords Match!";
} else {
c_passID.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = "Passwords Do Not Match!";
}
}
</script>
Okay so the issue was that you were attempting to change the color of the value of the c_pass and not the id itself. I renamed your variables to help you understand why it was breaking. Again this is only for the checkPass function. If you comment out all the other stuff and just use this script for now this will help you isolate the checkPass function and see that it works. I hope this helps.

Submit button is not getting enabled after checking all the fields

I have a sign up form where I have taken some basic details of the customer and a Submit button.
I have validate all the fields using ajax but confirm password field using javascript. When I write code only using Ajax and not validating Confirm password field it is running perfectly but the problem is when I am validation it using JS submit button is not getting enable.
Sign up form:
<html>
<head>
<title> Registration Form </title>
<script language="javascript">
var flag = false;
function validate(element)
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new Activexobject("Microsoft.XMLHTTP");
}
var myField = element;
xmlhttp.open('GET', 'validate.php?' + myField.id + "=" + myField.value, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function ()
{
//alert("Hello");
if (xmlhttp.readyState === 4 && xmlhttp.status === 200)
{
var response = xmlhttp.responseText.split("||");
//alert("H2");
}
var divname = "err" + myField.id.substring(3);
var mydiv = document.getElementById(divname);
if (!eval(response[0]))
{
//alert("Fail");
//alert("Value: "+response);
mydiv.innerHTML = response[1];
myField.valid = false;
}
else
{
//alert("Success");
myField.valid = true;
mydiv.innerHTML = "";
}
var btn = document.getElementById("btnSubmit");
btn.disabled = !isValidForm();
}
}
;
function password()
{
var pass = document.getElementById("txtpswd").value;
var Confirm_pass = document.getElementById("txtConfirmpassword").value;
alert("Pass " + pass);
alert("Confirm: " + Confirm_pass);
if (pass == Confirm_pass)
{
flag = true;
alert("True");
document.getElementById("errConfirmpassword").innerHTML = "";
}
else
{
alert("False");
flag = false;
document.getElementById("errConfirmpassword").innerHTML = "Password does not Match";
}
}
;
function isValidForm()
{
var f1 = document.getElementById("txtfname");
var f2 = document.getElementById("txtlname");
var f3 = document.getElementById("txtaddress");
var f4 = document.getElementById("txtzip");
var f5 = document.getElementById("txtnumber");
var f6 = document.getElementById("txtmail");
var f7 = document.getElementById("txtpswd");
var f8 = document.getElementById("txtConfirmpassword");
return(f1.valid && f2.valid && f3.valid && f4.valid && f5.valid && f6.valid && f7.valid && f8.valid);
}
;
</script>
</head>
<body>
<center>
<h1><font color="red"> New User Registration Form </font></h1>
<form name="SignUpForm" method="POST" action="function_customer.php?val=insert">
<table>
<tr>
<td id=q> <font face="Century Schoolbook"> First Name :</font></td> <br>
<td> <input type=text name=txtfname id="txtfname" placeholder=First_name onchange="validate(this);" valid=false> </td>
<td><div id="errfname"/></td>
</tr>
<tr>
<td id=q> Last Name :</td>
<td> <input type=text name=txtlname id="txtlname" placeholder=Last_Name onchange="validate(this);" valid=false> </td>
<td><div id="errlname"/></td>
</tr>
<tr>
<td id=q>Address : </td><br>
<td> <textarea rows=5 cols=20 name="txtaddress" id="txtaddress" onchange="validate(this);" valid=false>
</textarea>
</td>
<td><div id="erraddress"/></td>
</tr>
<tr>
<td id=q> Contact no : </td>
<td> <input type=text name="txtnumber" id="txtnumber" onchange="validate(this);" valid=false> </td>
<td><div id="errnumber"/></td>
</tr>
<tr>
<td id=q> Gender </td>
<td> <select name="txtcity" id="gender">
<option value="Male"> Male </option>
<option value="Female"> Female </option>
</select>
</td>
</tr>
<tr>
<td id=q> City </td>
<td>
<select name="txtcity" id="txtcity">
<option> City </option>
<option value="Vadodara"> Vadodara </option>
<option value="Ahmedabad"> Ahmedabad </option>
<option value="Surat"> Surat </option>
<option value="Rajkot"> Rajkot </option>
<option value="Bhavnagar">Bhavnagar</option>
<option value="Jamnagar">Jamnagar</option>
<option value="Nadidad">Nadidad</option>
<option value="Morvi">Morvi</option>
<option value="Gandhidham">Gandhidham</option>
<option value="Adipur">Adipur</option>
<option value="Anand">Anand</option>
<option value="Baruch">Baruch</option>
<option value="Godhra">Godhra</option>
<option value="Veraval">Veraval</option>
<option value="Navsari">Navsari</option>
</select>
</td>
</tr>
<tr>
<td id=q> ZIP : </td>
<td> <input type=text name=txtzip id="txtzip" onchange="validate(this);" valid=false> </td>
<td><div id="errzip"/></td>
</tr>
<tr>
<td id=q> Email Id : </td>
<td> <input type="email" name=txtmail placeholder=someone#exe.com id="txtmail" onchange="validate(this);" valid=false> </td>
<td><div id="errmail"/></td>
</tr>
<tr>
<td id=q> New Password : </td>
<td> <input type="password" name="txtpswd" id="txtpswd" onchange="validate(this);" valid=false>
</td>
<td><div id="errpswd"/></td>
</tr>
<tr>
<td id=q>Confirm Password : </td><td><input type="password" name=txtConfirmpassword id="txtConfirmpassword" onchange="password();" valid=false>
</td>
<td><div id="errConfirmpassword"/></td>
</tr>
<tr>
<td></td><td><input type=reset name=reset value=Reset>
</td>
</tr>
<tr>
</tr>
</table>
</form>
<br>
<br>
<br>
<br><br>
</center>
</body>
</html>
What should I do to validate all the fields and enabling the Submit Button?
First of all I suggest you read up on the latest HTML elements and use CSS for centering or styling your elements and avoid usage of obsolete elements like <font> and <center>.
Having said that, the issue in your code is that you're not calling validate() to check if the form is valid after password & confirm password fields match, so change your password() like below.
function password(){
var btn = document.getElementById("btnSubmit");
var pass = document.getElementById("txtpswd").value;
var confirm_pass = document.getElementById("txtConfirmpassword").value;
var pwdErrorElement = document.getElementById("errConfirmpassword");
if (pass === confirm_pass){
flag = true;
pwdErrorElement.innerHTML = "";
btn.disabled = !isValidForm();
}else{
flag = false;
pwdErrorElement.innerHTML = "Password does not Match";
btn.disabled = true;
}
}
Also I suggest you to make use of value property on each field to do the validations on client side rather than making a server call for every field change. You can use field values for validations by changing the last statement in your isValidForm() like below.
function isValidForm(){
// get all the field references
return(f1.value && f2.value && f3.value && f4.value
&& f5.value && f6.value && f7.value && f8.value);
}
Once you're done with the JS validations, you can enable the submit button and do validations for all fields at once on your server side on form submit. I mean that's the very purpose of doing client side validations using JS. You don't want to ask for feedback (valid or not) for every field change.
Here's a working Pen with all the above changes.

HTML form validation with Javascript

im a bit new using javascript in HTML. I want to validate a HTML script using javascript however what i've written doesn't seem to work. Can anyone tell me where I'm going wrong???
Here is the Javascript:
<script type="text/javascript">
function mandatoryFields()
{
var x=document.forms["add"]["contract_id"].value
if (x==null || x=="")
{
alert("Please Enter the Contract Title");
return false;
}
var x=document.forms["add"]["storydiv"].value
if (x==null || x=="")
{
alert("Please Enter a Sprint");
return false;
}
var x=document.forms["add"]["storydiv"].value
if (x==null || x=="")
{
alert("Please Enter a Story");
return false
}
var x=document.forms["add"]["date1"].value
if ( x=="" || x==null)
{
alert("Please Enter a time");
return false
}
</script>
And here is the corresponding HTML script
<form name="add" action="time-sheet/insert-time-sheet.php" method="post" onsubmit="return mandatoryFields()">
<table width="500" border="0" align="center" cellpadding="2" cellspacing="2">
<tr>
<td colspan="2"> </td>
</tr>
<tr>
<td width="150">Select Date:</td>
<td width="336"><input name="date" type="text" value="YYYY-MM-DD" maxlength="100" class="datepick" id="date1" /></td>
</tr>
<tr>
<td>Contract:</td>
<td><SELECT NAME="contract_id" onChange="getSprint(this.value)"><OPTION VALUE=0>--- Select Contract ---<?php echo $options_contract?></SELECT></td>
</tr>
<tr>
<td>Sprint:</td>
<td><div id="sprintdiv"><select name="sprint" >
<option>--- Select Sprint ---</option>
</select></div></td>
</tr>
<tr>
<td>Story:</td>
<td><div id="storydiv"><select name="story">
<option>--- Select Story ---</option>
</select></div></td>
</tr>
<tr>
<td>Dev Time:</td>
<td><input name="dev_time" size="20" onkeyup="ondalikSayiKontrol(this)" /></td>
</tr>
<tr>
<td>PM Time:</td>
<td><input name="pm_time" size="20" onkeyup="ondalikSayiKontrol(this)"/></td>
</tr>
<tr>
<td colspan="2"><table width="182" border="0" align="center" cellpadding="2" cellspacing="2">
<tr>
<td width="68"><input name="Submit" type="submit" id="Submit" value="Add Time Sheet" /></td>
<td width="48"><label>
<input type="reset" name="reset" value="Reset" />
</label></td>
<td width="46"><div align="center">Back</div></td>
</tr>
<input type="hidden" name="day" value="<?php echo $day; ?>" />
<input type="hidden" name="employee_id" value="<?php echo $employee_id; ?>" />
</table></td>
</tr>
<tr>
<td colspan="2"> </td>
</tr>
</table>
</form>
Thanks in advance!
You're missing the closing brace on the function. If you check the error console on your browser, it will most likely tell you mandatoryFields() is undefined. Adding the closing brace will fix that. You should also return true if none of the validation fails. One last thing is that you re-declare x before each if. Not sure if it produces an error but still should be fixed.
<script type="text/javascript">
function mandatoryFields()
{
var x=document.forms["add"]["contract_id"].value;
if (x==null || x=="")
{
alert("Please Enter the Contract Title");
return false;
}
x=document.forms["add"]["storydiv"].value;
if (x==null || x=="")
{
alert("Please Enter a Sprint");
return false;
}
x=document.forms["add"]["storydiv"].value;
if (x==null || x=="")
{
alert("Please Enter a Story");
return false;
}
x=document.forms["add"]["date1"].value;
if ( x=="" || x==null)
{
alert("Please Enter a time");
return false;
}
return true; // ADD THIS
} // ADD THIS
</script>
Your madatoryFields() function is not returning true when all fields are right.
from here:
If the event handler is called by the onsubmit attribute of the form
object, the code must explicitly request the return value using the
return function, and the event handler must provide an explicit return
value for each possible code path in the event handler function.
Get the right elements and perform a loop on the options inside of sprint and story.
You can use the name of your form and the names of your select boxes to access the elements straight forward.
var x = document.add.contract_id.value;
if(){
... your stuff here
}
You can also access the first form without using its name attribute.
x = document.forms[0].contract_id.value;
For sprint loop through possible options and make your alert then.
x = document.add.sprint;
var selected = false;
for (i = 0; i < x.length; ++i){
if (x.options[i].selected == true)
selected = true;
}
if(!selected){
alert("Select a story please!");
return false;
}
x = document.add.story;
selected = false;
// same procedure
You can also access the elements via getElementByID() and getElementsByTagName(), the latter returns an array of all matched elements.
document.getElementById('storydiv').getElementsByTagName('story')[0];
document.getElementsByTagName('contract_id')[0];
And dont redeclare var x in every validation step.

checkbox - check at least one box has been selected

To validate a statement I have made sure that the checkboxes and quantities are consistent with each other but I haven't made sure that at least one product has been selected or a total quantity greater than zero is supplied. How would I do this?
if (((document.form1.summer.checked) && (summer2012 <= 0)) ||
((document.form1.autumn.checked) && (autumn2012 <= 0)) ||
((document.form1.winter.checked) && (winter2012 <= 0)))
{
alertmsg = alertmsg + "Please enter Quantity" + "\n";
}
else if (((!document.form1.summer.checked) && (summer2012 > 0)) ||
((!document.form1.autumn.checked) && (autumn2012 > 0)) ||
((!document.form1.winter.checked) && (winter2012 > 0)))
{
alertmsg = alertmsg + "Please choose Product" + "\n";
}
HTML:
<tr>
<td align="right">Summer 2012</td>
<td>
<input type="checkbox" name="summer" value="Summer 2012" />
</td>
<td align="center" width="69">
<div align="right">20.00</div>
</td>
<td width="216">
<input name="summer2012" type="text" size="5" value="0" />
</td>
</tr>
<tr>
<td align="right">Autumn 2012</td>
<td>
<input type="checkbox" name="autumn" value="Autumn 2012" />
</td>
<td align="center" width="69">
<div align="right">20.00</div>
</td>
<td>
<input name="autumn2012" type="text" size="5" value="0" />
</td>
</tr>
<tr>
<td align="right">Winter 2012</td>
<td>
<input type="checkbox" name="winter" value="Winter 2012" />
</td>
<td align="center" width="69">
<div align="right">20.00</div>
</td>
<td>
<input name="winter2012" type="text" size="5" value="0" />
</td>
</tr>
You appear to already have a test to confirm that for any checked box there must be a corresponding (positive) amount, and a second test to confirm that any positive amount also has a check against it.
All you therefore need to do is check that some checkbox is checked.
var f = document.form1;
if (f.summer.checked || f.autumn.checked || f.winter.checked) {
// we're OK!
}
This is how I would check if any checkbox has been checked:
var checkboxElements = [
document.form1.ch1,
document.form1.autumn,
document.form1.winter,
document.form1.summer
];
function anyChecked(checkboxElements) {
for(var i = 0; i < checkboxElements.length; i++)
if(checkboxElements[i].checked)
return true;
return false;
}

how to make the validation of my web form just like yahoo registration page?

i am able to display an alert msg when my form fields are empty but i want to display a red colored msg in front of empty field just like in yahoo registration form i dont know how to do this can any one explain to understand it
function validate_form ( )
{
valid = true;
if ( document.form.login.value == "" )
{
valid = false;
document.getElementById("LoginError").visible=false;
}
else
{
document.getElementById("LoginError").visible=false;
}
if(document.form.password.value == "" )
{
valid = false;
document.getElementById("PasswordError").visible=false;
}
else
{
document.getElementById("PasswordError").visible=false;
}
return valid;
}
//-->
</script>
<form name="form" method="post" action="UserLogin" onSubmit="return validate_form();">
<table width="592" height="127" border="0">
<tr>
<td width="46" height="29"> </td>
<td colspan="3"><%! private Boolean bRecord = false;
private Boolean bLogin = false;
%>
<% if(request.getAttribute("signup") != null)
bRecord =(Boolean)request.getAttribute("signup");
else
bRecord = false;
if(request.getAttribute("invalidlogin") != null)
bLogin =(Boolean)request.getAttribute("invalidlogin");
else
bLogin = false;
if(bRecord == true )
{%>
<font color="#336600"><b>You are Successfully Signed Up</b></font>
<%
request.removeAttribute("signup");
}//end if
if(bLogin == true )
{%>
<font color="#FF0000"><b>Invalid Login or Password</b></font>
<%
request.removeAttribute("invalidlogin");
}//end if
%></td>
</tr>
<tr>
<td> </td>
<td width="135"><div class="style1">LOGIN: </div></td>
<td width="146"><input type="text" name="login"></td>
<td width="247">*<span id="LoginError" visible="false" style="color: Red;">Enter login</span>
</td>
</tr>
<tr>
<td> </td>
<td><div class="style1">PASSWORD: </div></td>
<td><input name="password" type="password" id="password"></td>
<td>*<span id="PasswordError" visible="false" style="color: Red;">enter Password</span></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td align="right"><input name="Submit" type="image" class="bgtop" value="SIGN IN" src="images/btn_s.JPG" border="0" >
</td>
<td> </td>
</tr>
</table>
</form>
regards
You can simply add a non-visible span in front of the field
<span id="spanUsernameRequired" style="visibility: hidden; color: Red;">
This information is required</span>
<input id="username" type="text" />
Submit
, and then make it visible when the field is empty
function validate_form()
{
if (document.getElementById("username").value == "")
{
document.getElementById("spanUsernameRequired").style.visibility = 'visible';
return false;
}
else
document.getElementById("spanUsernameRequired").style.visibility = 'hidden';
return true;
}

Categories