I would need a little help of you today, i'm wondering how can i validate my script for letters only on first 2 inputs?
I'm using javascript to validate my form below: I have managed to validate for email though and zip (numbers only)...
<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
<!--
function checkForEmail()
{
var emailID = document.myForm.EMail.value;
atpos = emailID.indexOf("#");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Alert")
document.myForm.EMail.focus() ;
return false;
}
return( true );
}
function validate()
{
if( document.myForm.Name.value == "" )
{
alert( "Alert" );
document.myForm.Name.focus() ;
return false;
}
if( document.myForm.Surname.value == "" )
{
alert( "Alert" );
document.myForm.Surname.focus() ;
return false;
}
if( document.myForm.EMail.value == "" )
{
alert( "Alert" );
document.myForm.EMail.focus() ;
return false;
}else{
var ret = checkForEmail();
if( ret == false )
{
return false;
}
}
if( document.myForm.zip.value == "" ||
isNaN( document.myForm.zip.value ) ||
document.myForm.zip.value.length != 13 )
{
alert( "Alert" );
document.myForm.zip.focus() ;
return false;
}
return( true );
}
//-->
</script>
</head>
<body>
<form action="/cgi-bin/test.cgi" name="myForm" onsubmit="return(validate());">
<table cellspacing="2" cellpadding="2" border="1">
<tr>
<td align="right">Name</td>
<td><input type="text" name="Name" /></td>
</tr>
<tr>
<td align="right">Surname</td>
<td><input type="text" name="Surname" /></td>
</tr>
<tr>
<td align="right">EMail</td>
<td><input type="text" name="EMail" /></td>
</tr>
<tr>
<td align="right">zip</td>
<td><input type="text" name="zip" /></td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
how can i validate my script for letters only on first 2 inputs
// Check s contains at least one letter and is only letters
function checkLettersOnly(s) {
return /^[a-z]+$/i.test(s);
}
if (!checkLettersOnly(document.myForm.Name.value)) {
// not letters only
}
Related
Good evening,
I currently have a HTML Form with a script to validate the field have data entry into them however after it validating all fields are filled it doesnt submit, can anybody please advise what is wrong? New to this so learning and would really appreciate any help possible.
I have attached the code im using below.
<div id="form">
<form name="contact" method="post" action="contact.php" onsubmit="return !!(validatename()&validateemail()&validatecomments()&validateRecaptcha());">
<table width="450px">
<tr>
<td valign="top"><label for="name">Name</label></td>
<td valign="top"><input type="text" name="name" maxlength="50" size="30"></td>
</tr>
<tr>
<td valign="top"><label for="email">Email Address</label></td>
<td valign="top"><input type="text" name="email" maxlength="80" size="30"></td>
</tr>
<tr>
<td valign="top"><label for="comments">Comments</label></td>
<td valign="top"><textarea name="comments" maxlength="1000" cols="32" rows="8"></textarea></td>
</tr>
<tr>
<td colspan="2" style="text-align:center">
<div id="form" class="g-recaptcha" data-sitekey="6LdcZFkUAAAAAFoHAYtupqKzCgd2T9XzHZFj8XNw"></div>
<input type="image" src="images/submit.png" alt="Submit">
</td>
</tr>
</table>
</form>
<script>
function validatename()
{
if( document.contact.name.value == "" )
{
alert( "Please provide your name!" );
document.contact.name.focus() ;
return false ;
}
}
function validateemail()
{
if( document.contact.email.value == "" )
{
alert( "Please provide your email address!" );
document.contact.email.focus() ;
return false ;
}
}
function validatecomments()
{
if( document.contact.comments.value == "" )
{
alert( "Please provide your comments!" );
document.contact.comments.focus() ;
return false ;
}
}
function validateRecaptcha() {
var response = grecaptcha.getResponse();
if (response.length === 0) {
alert("You need to fill the captcha");
return false ;
}
}
</script>
This is one way how you could do it:
function validatename() {
if (document.contact.name.value == "") {
alert("Please provide your name!");
document.contact.name.focus();
return false;
}
else {
return true;
}
}
function validateemail() {
if (document.contact.email.value == "") {
alert("Please provide your email address!");
document.contact.email.focus();
return false;
}
else {
return true;
}
}
function validatecomments() {
if (document.contact.comments.value == "") {
alert("Please provide your comments!");
document.contact.comments.focus();
return false;
}
else {
return true;
}
}
function validateRecaptcha() {
var response = grecaptcha.getResponse();
if (response.length === 0) {
alert("You need to fill the captcha");
return false ;
}
else {
return true;
}
}
document.getElementById('my-form').addEventListener('submit', function(e) {
e.preventDefault();
if (validatename() && validateemail() && validatecomments() && validateRecaptcha()) {
var formValidation = true;
}
else {
var formValidation = false;
}
if (formValidation) {
this.submit();
}
});
<div id="form">
<form id="my-form" name="contact" method="post" action="contact.php">
<table width="450px">
<tr>
<td valign="top"><label for="name">Name</label></td>
<td valign="top"><input type="text" name="name" maxlength="50" size="30"></td>
</tr>
<tr>
<td valign="top"><label for="email">Email Address</label></td>
<td valign="top"><input type="text" name="email" maxlength="80" size="30"></td>
</tr>
<tr>
<td valign="top"><label for="comments">Comments</label></td>
<td valign="top"><textarea name="comments" maxlength="1000" cols="32" rows="8"></textarea></td>
</tr>
<tr>
<td colspan="2" style="text-align:center">
<div id="form" class="g-recaptcha" data-sitekey="6LdcZFkUAAAAAFoHAYtupqKzCgd2T9XzHZFj8XNw"></div>
<input type="image" src="images/submit.png" alt="Submit">
</td>
</tr>
</table>
</form>
</div>
To make it work correctly, make sure that grecaptcha is defined.
I am new In jquery created validation and calculation using formula.I have created six input fields.created validation all fields.but when empty all fields click calculation red star symbol showing first two fields not showing remain four fields please help me friends
here my code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="http://code.jquery.com/jquery-1.11.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
function calculate() {
var answer = 0;
if (validate()) {
var valueA = $("#valuea").val()
var valueB = $("#valueb").val()
var valueC = $("#valuec").val()
var valueD = $("#valued").val()
var valueE = $("#valuee").val()
var valueF = $("#valuef").val()
if (valueA && valueB && valueC && valueD && valueE && valueF) {
answer = ((parseFloat(valueB / valueA)) + (parseFloat(valueD / valueC)) + (parseFloat(valueF / valueE))) / 3;
}
else {
if (valueA && valueB && valueC && valueD)
answer = ((parseFloat(valueB / valueA)) + (parseFloat(valueD / valueC))) / 2;
else {
if (valueA && valueB && valueE && valueF)
answer = ((parseFloat(valueB / valueA)) + (parseFloat(valueF / valueE))) / 2;
else (valueA && valueB)
answer = ((parseFloat(valueB / valueA)));
}
}
if (parseFloat(answer) > .0238)
alert("Your Effective Rate = " + parseFloat(answer * 100).toFixed(2));
else if (answer == 0)
alert("Your Effective Rate:0.00% ");
else
alert("Oops, something has gone terribly wrong!Please attach at least 2 months of your most recent credit card processing statements and one of our specialists will respond within 24 hours with an accurate cost analysis");
}
return false;
}
function validate() {
var status = false;
var valueA = $("#valuea").val()
var valueB = $("#valueb").val()
var valueC = $("#valuec").val()
var valueD = $("#valued").val()
var valueE = $("#valuee").val()
var valueF = $("#valuef").val()
if (valueA) {
$("#spana").hide();
status = true;
}
else {
$("#spana").show();
status = false;
}
if (valueB) {
status = true;
$("#spanb").hide();
}
else {
status = false;
$("#spanb").show();
}
if (valueC && !valueD) {
status = false;
$("#spand").show();
$("#spanc").hide();
}
if (!valueC && valueD) {
status = false;
$("#spanc").show();
$("#spand").hide();
}
if (valueE && !valueF) {
status = false;
$("#spanf").show();
$("#spane").hide();
}
if (!valueE && valueF) {
status = false;
$("#spane").show();
$("#spanf").hide();
}
if (valueC && valueD) {
$("#spand").hide();
$("#spanc").hide();
return true;
}
if (valueE && valueF) {
status = true;
$("#spane").hide();
$("#spanf").hide();
}
return status;
}
</script>
</head>
<body>
<form>
<table class="calculator" border='0' width='500px' cellpadding='3' cellspacing='1'
class="table">
<tr class="calcheading">
<td colspan="3" align="center">
Whats your effective rate?
</td>
</tr>
<tr class="monthheading">
<td colspan="2">
<strong>Month 1</strong>
</td>
</tr>
<tr class="calcrow">
<td>
Total Sales, Including Amex
</td>
<td align="center">
<input type='text' name='valuea' id="valuea" onkeypress="return isNumber(event)"
autocomplete="off" />
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spana">*</span>
</td>
</tr>
<tr class="calcrow2">
<td>
Total Fees, less any terminal or rental fees
</td>
<td align="center">
<input type='text' name='valueb' id="valueb" onkeypress="return isNumber(event)"
autocomplete="off" />
</td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spanb">*</span>
</td>
</tr>
<tr class="monthheading">
<td colspan="2">
<strong>Month 2</strong>
</td>
</tr>
<tr class="calcrow">
<td>
Total Sales, Including Amex
</td>
<td align="center">
<input type='text' name='valuec' id="valuec" onkeypress="return isNumber(event)"
autocomplete="off" />
</td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spanc">*</span>
</td>
</tr>
<tr class="calcrow2">
<td>
Total Fees, less any terminal or rental fees
</td>
<td align="center">
<input type='text' name='valued' id="valued" onkeypress="return isNumber(event)"
autocomplete="off" />
</td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spand">*</span>
</td>
</tr>
<tr class="monthheading">
<td colspan="2">
<strong>Month 3</strong>
</td>
</tr>
<tr class="calcrow">
<td>
Total Sales, Including Amex
</td>
<td align="center">
<input type='text' name='valuee' id="valuee" onkeypress="return isNumber(event)"
autocomplete="off" />
</td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spane">*</span>
</td>
</tr>
<tr class="calcrow2">
<td>
Total Fees, less any terminal or rental fees
</td>
<td align="center">
<input type='text' name='valuef' id="valuef" onkeypress="return isNumber(event)"
autocomplete="off" />
</td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spanf">*</span>
</td>
</tr>
<tr class="submit">
<td colspan="3" align="center">
<input type='submit' value='Calculate' onclick="return calculate();" />
</td>
</tr>
<tr class="calcrow">
<td colspan="3" align="center">
</td>
</tr>
</table>
</form>
</body>
</html>
calculation all working good.when leave fields empty click calculation show red star required first two column remain not showing help me friends
There is a mistake in the condition you have written for the valueC,valueD, valueE and valueF. You should continue as of valueA and valueA for the remaining too, if you want to achieve the functionality as you are trying to.
But, My Suggestion is to Use http://jqueryvalidation.org/ Plugin for validating the elements. It is very handy to use and customize as required.
Thank you
Check you conditions. small logical mistakes in your conditions. for eg.
if (valueC && !valueD) {
status = false;
$("#spand").show();
$("#spanc").hide();
}
if (!valueC && valueD) {
status = false;
$("#spanc").show();
$("#spand").hide();
}
This will check if either valuec or valued is empty. You are not checking for both empty. You need to add something like this
if (!valueC && !valueD) {
status = false;
$("#spand").show();
$("#spanc").hide();
}
Brother its not a good trick to make your code lengthy. You could achieve your goal by using each function. Below is an example of doing that. Please have a look.
function validate(){
var formValidate = true;
jQuery(form + " select," + form + " input").each(
function (index) {
var input = jQuery(this);
if (input.val() == "" ) {
input.addClass("error");
input.parent().next("td").fadeIn("slow");
}
else {
input.removeClass("error");
input.parent().next("td").fadeOut("slow");
}
if (input.hasClass('error')) {
if (formValidate == true) {
formValidate = false;
}
}
}
);
if (formValidate == true) {
return true;
}
else {
return false;
}
}
exact solution to your answer is below please copy n paste then check.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="../jQuery/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
function calculate() {
var answer = 0;
if (validate()) {
var valueA = $("#valuea").val()
var valueB = $("#valueb").val()
var valueC = $("#valuec").val()
var valueD = $("#valued").val()
var valueE = $("#valuee").val()
var valueF = $("#valuef").val()
if (valueA && valueB && valueC && valueD && valueE && valueF) {
answer = ((parseFloat(valueB / valueA)) + (parseFloat(valueD / valueC)) + (parseFloat(valueF / valueE))) / 3;
}
else {
if (valueA && valueB && valueC && valueD)
answer = ((parseFloat(valueB / valueA)) + (parseFloat(valueD / valueC))) / 2;
else {
if (valueA && valueB && valueE && valueF)
answer = ((parseFloat(valueB / valueA)) + (parseFloat(valueF / valueE))) / 2;
else (valueA && valueB)
answer = ((parseFloat(valueB / valueA)));
}
}
if (parseFloat(answer) > .0238)
alert("Your Effective Rate = " + parseFloat(answer * 100).toFixed(2));
else if (answer == 0)
alert("Your Effective Rate:0.00% ");
else
alert("Oops, something has gone terribly wrong!Please attach at least 2 months of your most recent credit card processing statements and one of our specialists will respond within 24 hours with an accurate cost analysis");
}
return false;
}
function validate() {
var status = false;
var valueA = $("#valuea").val()
var valueB = $("#valueb").val()
var valueC = $("#valuec").val()
var valueD = $("#valued").val()
var valueE = $("#valuee").val()
var valueF = $("#valuef").val()
if (valueA) {
$("#spana").hide();
status = true;
}
else {
$("#spana").show();
status = false;
}
if (valueB) {
status = true;
$("#spanb").hide();
}
else {
status = false;
$("#spanb").show();
}
if (valueC && !valueD) {
status = false;
$("#spand").show();
$("#spanc").hide();
}
if (!valueC && valueD) {
status = false;
$("#spanc").show();
$("#spand").hide();
}
if (valueE && !valueF) {
status = false;
$("#spanf").show();
$("#spane").hide();
}
if (!valueE && valueF) {
status = false;
$("#spane").show();
$("#spanf").hide();
}
if (valueC && valueD) {
$("#spand").hide();
$("#spanc").hide();
return true;
}
if (valueE && valueF) {
status = true;
$("#spane").hide();
$("#spanf").hide();
}
//change is here
//change status value as per your requirement
if (!valueC && !valueD) {
//status = false;
$("#spand").show();
$("#spanc").show();
}
if (!valueE && !valueF) {
//status = false;
$("#spanf").show();
$("#spane").show();
}
return status;
}
</script>
</head>
<body>
<form>
<table class="calculator" border='0' width='500px' cellpadding='3' cellspacing='1' class="table">
<tr class="calcheading">
<td colspan="3" align="center">
Whats your effective rate?
</td>
</tr>
<tr class="monthheading">
<td colspan="2">
<strong>Month 1</strong>
</td>
</tr>
<tr class="calcrow">
<td>
Total Sales, Including Amex
</td>
<td align="center">
<input type='text' name='valuea' id="valuea" onkeypress="return isNumber(event)"
autocomplete="off" /></td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spana">*</span>
</td>
</tr>
<tr class="calcrow2">
<td>
Total Fees, less any terminal or rental fees
</td>
<td align="center">
<input type='text' name='valueb' id="valueb" onkeypress="return isNumber(event)"
autocomplete="off" />
</td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spanb">*</span>
</td>
</tr>
<tr class="monthheading">
<td colspan="2">
<strong>Month 2</strong>
</td>
</tr>
<tr class="calcrow">
<td>
Total Sales, Including Amex
</td>
<td align="center">
<input type='text' name='valuec' id="valuec" onkeypress="return isNumber(event)"
autocomplete="off" />
</td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spanc">*</span>
</td>
</tr>
<tr class="calcrow2">
<td>
Total Fees, less any terminal or rental fees
</td>
<td align="center">
<input type='text' name='valued' id="valued" onkeypress="return isNumber(event)"
autocomplete="off" />
</td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spand">*</span>
</td>
</tr>
<tr class="monthheading">
<td colspan="2">
<strong>Month 3</strong>
</td>
</tr>
<tr class="calcrow">
<td>
Total Sales, Including Amex
</td>
<td align="center">
<input type='text' name='valuee' id="valuee" onkeypress="return isNumber(event)"
autocomplete="off" />
</td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spane">*</span>
</td>
</tr>
<tr class="calcrow2">
<td>
Total Fees, less any terminal or rental fees
</td>
<td align="center">
<input type='text' name='valuef' id="valuef" onkeypress="return isNumber(event)"
autocomplete="off" />
</td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spanf">*</span>
</td>
</tr>
<tr class="submit">
<td colspan="3" align="center">
<input type='submit' value='Calculate' onclick="return calculate();" />
</td>
</tr>
<tr class="calcrow">
<td colspan="3" align="center">
</td>
</tr>
</table>
</form>
</body>
</html>
If you really want to do it in that way consider below validation method.
I assume what you want is to check the input fields are empty or not. what you have done is still unclear to me.
To do a proper validation you need to identify and state what should be checked and how should they handled as well.
function validate() {
var status = false;
var valueA = $("#valuea").val();
var valueB = $("#valueb").val();
var valueC = $("#valuec").val();
var valueD = $("#valued").val();
var valueE = $("#valuee").val();
var valueF = $("#valuef").val();
if (valueA) {
$("#spana").hide();
status = true;
}
else {
$("#spana").show();
status = false;
}
if (valueB) {
$("#spanb").hide();
status = true;
}
else {
$("#spanb").show();
status = false;
}
if (valueC) {
$("#spanc").hide();
status = true;
}
else {
$("#spanc").show();
status = false;
}
if (valueD) {
$("#spand").hide();
status = true;
}
else {
$("#spand").show();
status = false;
}
if (valueE) {
$("#spane").hide();
status = true;
}
else {
$("#spane").show();
status = false;
}
if (valueF) {
$("#spanf").hide();
status = true;
}
else {
$("#spanf").show();
status = false;
}
return status;
}
i am having this problem where those validation stopped working starting from the email validation part onwards.
i just couldn't figure out why even after days looking at it and just wondering if someone can point out my mistake here?
Javascript part:
function validateForm()
{
var x=document.forms["myForm"]["firstname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
var x=document.forms["myForm"]["lastname"].value;
if (x==null || x=="")
{
alert("Last name must be filled out");
return false;
}
var x=document.forms["myForm"]["age"].value;
if (x==null || x=="" || x < 18 || x > 110 || isNaN(x))
{
alert("Age must be 18-110");
return false;
}
var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length)
{
alert("Not a valid e-mail address");
return false;
}
var x=document.forms["myForm"]["phone"].value;
var pattern = /^\(?([0-9]{2})\)?[ ]+([0-9]{4})[ ]+([0-9]{4})$/;
if (x==null || x=="")
{
alert("Not a valid phone number");
return false;
} else if (x.match(pattern)) {
return true;
} else {
alert ("Phone number must be in the following format: xx xxxx xxxx");
return false;
}
}
and this is the form part:
<form id="myForm" action="../includes/create-user.php" onsubmit="return validateForm();" method="post">
<div id = "table">
<table>
<tr>
<td>First Name: </td>
<td><input type="text" name="firstname" id="firstname"/></td>
</tr>
<tr>
<td>Last Name: </td>
<td><input type="text" name="lastname" id="lastname"/></td>
</tr>
<tr>
<td>Age: </td>
<td><input type="text" name="age" id="age"/></td>
</tr>
<tr>
<td>E-mail (username): </td>
<td><input type="text" name="user" id="user1"/></td>
</tr>
<tr>
<td>Password: </td>
<td><input type="password" name="pass" id="pass1"/></td>
</tr>
<tr>
<td>Phone: </td>
<td><input type="text" name="phone" id="phone"/></td>
</tr>
</table>
</div>
<div>
<input type="submit" name="submit" id="submit" value="Register"/>
</div>
</form>
The first thing that stands out is that you specify your field:
<td><input type="text" name="user" id="user1"/></td>
with id = 'user1'
and you look in your script for email
var x=document.forms["myForm"]["email"].value;
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! :)
i am working on project using php,html,javascript. i am using on blur and onsubmit both the functions to provide dynamic kind of feel for errors. the following logic is working in every file except for this one .
The form functions like onsubmit and onblur are not working , i used an alert also to check but its not being called could someone please check and tell me where i am going wrong
<script language="Javascript">
//the flags are used to check if all the fields are filled and none is empty
var flag1;
var flag2;
var flag3;
function test(){
alert("fn called");
return true;
}
function fun1()
{
var donated_date=document.forms["myform"]["donated_date"];
if(donated_date==null||donated_date=="")
{
document.getElementById('ddate').innerHTML = "Choose the date of your last donation " ;
document.getElementById('ddate').style.display = "block" ;
flag1=false;
return false;
}
document.getElementById('ddate').style.display = "none" ;
flag1=true;
return true;
}
function fun2()
{
var location=document.forms["myform"]["location"];
if(location==null||location==""||!isNaN(location))
{
document.getElementById('loc').innerHTML = "Mention the location of your last donation " ;
document.getElementById('loc').style.display = "block" ;
flag2=false;
return false;
}
document.getElementById('loc').style.display = "none" ;
flag2=true;
return true;
function fun3()
{
var hospital_name=document.forms["myform"]["hospital_name"];
if(hospital_name==null||hospital_name==""||!isNaN(hospital_name))
{
document.getElementById('hname').innerHTML = "Mention the Hospital Name where you last donated " ;
document.getElementById('hname').style.display = "block" ;
flag3=false;
return false;
}
document.getElementById('hname').style.display = "none" ;
flag3=true;
return true;
}
function validate()
{
alert("hello");
}
</script>
<form name="myform" method="post" action="o.php" onsubmit="return validate()">
<table width="94%" cellpadding="3px" class=" lastDonatedblood_table" cellspacing="0" style="border: 1px solid #CCCCCC;margin: -18px 0 14px 6px;width: 98.5%;">
<tr>
<td style="text-align:left;">Donated Date:</td>
<td style="text-align:left;">
<input type="text" name="donated_date" id="donated_date" onblur="return test();" style="width:300px;"/>
<div id="ddate"></div>
</td>
</tr>
<tr>
<td style="text-align:left;">Location:</td>
<td style="text-align:left;"><textarea name="location" id="location" onblur="return fun2();" style="width:300px;"></textarea></td>
</tr>
<center></center>
<tr>
<td style="text-align:left;">Hospital Name:</td>
<td style="text-align:left;"><input type="text" name="hospital_name" id="hospital_name" onblur="return fun3();" style="width:300px;"/></td>
</tr>
<center><div id="hname"></div></center>
<tr>
<td style="text-align:left;">Type of Donation:</td>
<td style="text-align:left;">
<select title="" name="donationtype" id="donationtype" style="width:317px;">
<option value="blood">Blood</option>
<option value="platelets">Platelets</option>
</select>
</td>
</tr>
<tr >
<td colspan="2">
<input name="submit" id="submit" value="ADD" type="submit" style="margin-top:5px; margin-left:185px; font-size:14px; width:100px;">
</td>
</tr>
</table>
</form>
you are missing closing curly bracket (function close) for fun2(),
function fun2()
{
var location=document.forms["myform"]["location"];
if(location==null||location==""||!isNaN(location))
{
document.getElementById('loc').innerHTML = "Mention the location of your last donation " ;
document.getElementById('loc').style.display = "block" ;
flag2=false;
return false;
}
document.getElementById('loc').style.display = "none" ;
flag2=true;
return true;
} <-- added closing curly bracket here
Check in console and you will get the error