Radio Button Validation Error - javascript

For the gender radio button validation within the validate function below, the alert occurs whenever neither of the gender radio buttons are selected. However, whenever "ok" is selected within the browser, the form is submitted. What seems to be causing that problem? Also I would like for it to be focused like the rest when returned false, if that is possible.
JavaScript
function validate()
{
var gender = document.getElementsByName("gender");
if( document.myForm.firstname.value == "" )
{
alert( "Please provide your first name!" );
document.myForm.firstname.focus() ;
return false;
}
if( document.myForm.lastname.value == "" )
{
alert( "Please provide your last name!" );
document.myForm.lastname.focus() ;
return false;
}
if( document.myForm.email.value == "" )
{
alert( "Please provide your email!" );
document.myForm.email.focus() ;
return false;
}
if( (gender[0].checked == false) && (gender[1].checked == false))
{
alert( "Please provide your gender!" );
document.myForm.male.focus() ;
return false;
}
if( document.myForm.date.value == "" )
{
alert( "Please provide a date to be performed!" );
document.myForm.date.focus() ;
return false;
}
if( document.myForm.vname.value == "" )
{
alert( "Please provide a victim's name!" );
document.myForm.vname.focus() ;
return false;
}
if( document.myForm.vemail.value == "" )
{
alert( "Please provide the victim's email!" );
document.myForm.vemail.focus() ;
return false;
}
return( true );
}
HTML:
<div id="box">
<form action="/cgi-bin/test.cgi" name="myForm" onsubmit="return(validate());">
<h1> Truth </h1>
<label> First Name: </label> <input type="text" name="firstname" id="firstname" maxlength="30" placeholder="John" /> <br><br>
<label> Last Name: </label> <input type="text" name="lastname" id="lastname" maxlength="30" placeholder="Doe" /> <br><br>
<label> Email:</label> <input type="text" name="email" id="email" placeholder="user#mydomain.com" /> <br><br>
<label> Male </label><input type="radio" name="gender" id="gender" value="male"/>
<label> Female </label><input type="radio" name="gender" id="gender" value="female"/> <br><br>
<label> Date to be performed: </label><input type="date" name="date" id="date" /><br><br>
<h2> Victim </h2>
<label> Name: </label> <input type="text" name="vname" id="vname" maxlength="30" placeholder="Mary Jane" /><br><br>
<label> Email:</label> <input type="text" name="vemail" id="vemail" placeholder="user#mydomain.com" /> <br><br>
<h2> Please select a truth questions below </h2> <br>
<input type="radio" name="truth" value="q1"> Have you ever fallen and landed on your head? <br>
<input type="radio" name="truth" value="q2"> Have you ever return too much change? <br>
<input type="radio" name="truth" value="q3"> Have you ever been admitted into the hospital? <br>
<input type="radio" name="truth" value="q4"> Have you ever baked a cake? <br>
<input type="radio" name="truth" value="q5"> Have you ever cheated on test? <br>
<input type="radio" name="truth" value="q6"> Did you ever wish you were never born? <br>
<input type="radio" name="truth" value="q7"> Did you ever hide from Sunday School? <br><br>
<input type="submit" value="Submit"/> <br>
</form>
</div>

I've figured out the solution. Instead of having:
if( (gender[0].checked == false) && (gender[1].checked == false))
{
alert( "Please provide your gender!" );
document.myForm.male.focus() ;
return false;
}
It should be:
if( (gender[0].checked == false) && (gender[1].checked == false))
{
alert( "Please provide your gender!" );
document.myForm.male.focus() ;
return true;
}
I did this & the validation is working perfectly.

Just provide a default for gender.
<input type="radio" name="gender" id="gender" value="male" checked/>
This will avoid any possible confusion and requires less validation overall.

You are defining your validate() function but I don't see you actually calling it when you submit the document. A submit input on it's own does not know about your validation.
Maybe change:
<input type="submit" value="Submit"/>
to
<input type="button" value="Submit" onClick="if(validate==true) {document.forms[0].submit()}" />

I would select according to different IDs naming them male and female and and call the validate function as ElPedro suggests.

I think it was issue with the focus function.
I made few changes and it worked.
<div id="box">
<form action="/cgi-bin/test.cgi" name="myForm" onsubmit="return validate();">
<h1> Truth </h1>
<label> First Name: </label> <input type="text" name="firstname" id="firstname" maxlength="30" placeholder="John" /> <br><br>
<label> Last Name: </label> <input type="text" name="lastname" id="lastname" maxlength="30" placeholder="Doe" /> <br><br>
<label> Email:</label> <input type="text" name="email" id="email" placeholder="user#mydomain.com" /> <br><br>
<label> Male </label><input type="radio" name="gender" id="gender" value="male"/>
<label> Female </label><input type="radio" name="gender" id="gender" value="female"/> <br><br>
<label> Date to be performed: </label><input type="date" name="date" id="date" /><br><br>
<h2> Victim </h2>
<label> Name: </label> <input type="text" name="vname" id="vname" maxlength="30" placeholder="Mary Jane" /><br><br>
<label> Email:</label> <input type="text" name="vemail" id="vemail" placeholder="user#mydomain.com" /> <br><br>
<h2> Please select a truth questions below </h2> <br>
<input type="radio" name="truth" value="q1"> Have you ever fallen and landed on your head? <br>
<input type="radio" name="truth" value="q2"> Have you ever return too much change? <br>
<input type="radio" name="truth" value="q3"> Have you ever been admitted into the hospital? <br>
<input type="radio" name="truth" value="q4"> Have you ever baked a cake? <br>
<input type="radio" name="truth" value="q5"> Have you ever cheated on test? <br>
<input type="radio" name="truth" value="q6"> Did you ever wish you were never born? <br>
<input type="radio" name="truth" value="q7"> Did you ever hide from Sunday School? <br><br>
<input type="submit" value="Submit"/> <br>
</form>
</div>
<script>
function validate(e)
{
var gender = document.getElementsByName("gender");
if( document.myForm.firstname.value == "" )
{
alert( "Please provide your first name!" );
return false;
}
if( document.myForm.lastname.value == "" )
{
alert( "Please provide your last name!" );
return false;
}
if( document.myForm.email.value == "" )
{
alert( "Please provide your email!" );
return false;
}
if( (gender[0].checked == false) && (gender[1].checked == false))
{
alert( "Please provide your gender!" );
return false;
}
if( document.myForm.date.value == "" )
{
alert( "Please provide a date to be performed!" );
return false;
}
if( document.myForm.vname.value == "" )
{
alert( "Please provide a victim's name!" );
return false;
}
if( document.myForm.vemail.value == "" )
{
alert( "Please provide the victim's email!" );
return false;
}
return true;
}
</script>

dont know if is the right answer but i uses that way and after evething i pass the variable value as my defined wish and passes to the form :)
var swticher = document.getElementById('swticher-on');
var swticher_off = document.getElementById('swticher-off');
function check(e){
if(e.checked == swticher.checked)
{
// you can set the value for on as default by set valirable in it
var val = swticher.value = "1";
alert('on -> '+val);
}
else if(e.checked == swticher_off.checked)
{
// you can set the value for off as default by set valirable in it
var val = swticher.value = "0";
alert('off -> '+val);
}
}
<!-- i dont know this is the right answer but i use this way somethings -->
<div class="col-sm-2">
<input type="radio" id="swticher-on" name="swticher" value="1" class="form-control swticher-in" onclick="check(this)">
<label for="swticher-on">ON</label>
</div>
<div class="col-sm-2">
<input type="radio" id="swticher-off" name="swticher" value="0" class="form-control swticher-in" checked onclick="check(this)">
<label for="swticher-off"><b class="text-danger">OFF</b></label>
</div>

Related

Why doesn't Javascript validate my html code?

This is my first attempt at working with javascript and forms; for some reason my html website elements aren't being validated and I am not sure why. My goal with this form is trying to validate the elements that have an '*' next to them. For some reason the only element that is being validated is email and nothing else. Name, dates, the checkbox aren't. I have been trying to find a fix, but nothing seems to work.
<!doctype html>
<html>
<head>
<link href="styles.css" rel="stylesheet">
<script src="script.js"></script>
<meta charset="utf-8">
<title>Form</title>
</head>
<body>
<div class="container">
<h1>Travel Reservation Form</h1>
<h4>* denotes mandotory field</h4>
<form name="myForm" action="action_page.php" onsubmit="return validateForm()" method="post">
<fieldset>
<legend>Personal Details</legend>
<label class="align">Full name:<span>*</span></label> <input type="text" name="fullname" placeholder="James Bond">
<br><br>
<label class="align">Email<span>*</span></label>
<input type="email" name="mail" placeholder="james#gmail.com">
<br><br>
<label class="align">Date of Birth<span>*</span></label> <input type="date" name="DOB" placeholder="dd/mm/yy">
</fieldset>
<br>
<label>Select Tour Package<span>*</span>:</label>
<select name="package">
<option value="1">Tokyo</option>
<option value="2">Shanghai</option>
<option value="3">Bangkok</option>
<option value="4">Jakarta</option>
<option value="5">Mumbai</option>
</select>
<label>Number of persons<span>*</span>:</label>
<select name="party">
<option value="1">One Adult</option>
<option value="2">Two Adults</option>
<option value="3">Three Adults</option>
<option value="4">Four Adults</option>
<option value="5">Five Adults</option>
</select>
<br><br>
<label>Arrival Date<span>*</span>:</label> <input type="date" name="arrival" placeholder="dd/mm/yy">
<br><br>
<p>What Intrests you the most?<span>*</span>:</p>
<input class="alignp" type="checkbox" name="interest" value="shopping"> Shopping <br><br>
<input class="alignp" type="checkbox" name="interest" value="dining"> Dining <br><br>
<input class="alignp" type="checkbox" name="interest" value="dancing"> Dancing <br><br>
<input class="alignp" type="checkbox" name="interest" value="SightS"> Sightseeing <br><br><br>
<label>Discount Coupon code:</label> <input type="text" name="dis_code" value=""><br><br>
<label>Terms and Conditions<span>*</span><input type="radio" name="tos" value="yes" checked>I agree</label>
<input type="radio" name="tos" value="yes">I disagree
<p>Please provide any additional information below:- </p>
<textarea name="message" rows="5" cols="45" placeholder="Please type here...."></textarea><br><br>
<button class="btn-submit" type="submit" value="Submit">Submit</button>
<button class="btn-reset" type="reset" value="Reset">Reset</button>
</form>
</div>
</body>
</html>
Here is the javascript that is being linked in the html. I am unsure whether the issue is with my html code or with my javascript.
// JavaScript Document
function validateForm()
{
var name = document.forms["myForm"]["name"].value;
var email = document.forms["myForm"]["email"].value;
var dob = document.forms["myForm"]["DOB"].value;
var packages = document.forms["myForm"]["package"].value;
var arrival = document.forms["myForm"]["arrival"].value;
//var interest = document.forms["form"]["interest"].value;
var ToS = document.forms["myForm"]["tos"].value;
var checkbox = document.querySelector('input[name="interest"]:checked');
var matches = name.match(/\d+/g);
if (matches != null) {
alert("Name has a number in it!");
}
if (name == "") {
alert("Name must be filled out");
return false;
}
if (email == "") {
alert("Email must be filled out");
return false;
}
if (dob == "") {
alert("Date of Birth must not be empty");
return false;
}
if (arrival == "") {
alert("Arrival Date must not be empty");
return false;
}
if(ToS == false) {
alert("You must agree to the Terms of Service");
return false;
}
if(validateEmail(email) == false){
alert("Must enter a valid email");
}
re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
if(dob != '' && !dob.match(re)) {
alert("Invalid date format");
return false;
}
if(arrival != '' && !arrival.match(re)) {
alert("Invalid arrival date format") ;
return false;
}
if(name.length >= 30){
alert("Name must be less than 30 characters!");
return false;
}
if(!checkbox){
alert("Please select an interest!");
return false;
}
}
function validateEmail(email)
{
return /\S+#\S+\.\S+/.test(email);
}
So I have no idea what your PHP form did, so I actually just pulled all the form code for now. There were a lot of little issues but honest mistakes. Example: you don't want a return statement after every validation if you want to continue validating the rest of the fields. I combined some separate validations into if/else's since they were validations on the same field. I used ID's to make my life easier and since I dumped the form code. Feel free to swap back to what you want. I also updated your regex since the date field returns YYYY/MM/DD. Since this doesn't post anywhere you can play with it for a while, before tying back into your php form. I also pulled the check for 30 characters and added a max field length to name. You could also set min and max date ranges for the date fields and a bunch of other things to help make the fields themselves more foolproof. There are also libraries that handle this kind of thing for you, you don't have to re-invent the wheel, but if you're just looking to play around with it this should get you started. Good Luck
<!doctype html>
<html>
<body>
<div class="container">
<h1>Travel Reservation Form</h1>
<h4>* denotes mandotory field</h4>
<fieldset>
<legend>Personal Details</legend>
<label class="align">Full name:<span>*</span></label> <input type="text" name="fullname" id='name' maxlength="30" placeholder="James Bond">
<br><br>
<label class="align">Email<span>*</span></label>
<input id="email" type="email" name="mail" placeholder="james#gmail.com">
<br><br>
<label class="align">Date of Birth<span>*</span></label> <input type="date" id="dob" name="DOB" placeholder="dd/mm/yy">
</fieldset>
<br>
<label>Select Tour Package<span>*</span>:</label>
<select id='package' name="package">
<option value="1">Tokyo</option>
<option value="2">Shanghai</option>
<option value="3">Bangkok</option>
<option value="4">Jakarta</option>
<option value="5">Mumbai</option>
</select>
<label>Number of persons<span>*</span>:</label>
<select name="party">
<option value="1">One Adult</option>
<option value="2">Two Adults</option>
<option value="3">Three Adults</option>
<option value="4">Four Adults</option>
<option value="5">Five Adults</option>
</select>
<br><br>
<label>Arrival Date<span>*</span>:</label> <input type="date" name="arrival" id="arrival" placeholder="dd/mm/yy">
<br><br>
<p>What Intrests you the most?<span>*</span>:</p>
<input class="alignp" type="checkbox" name="interest" value="shopping"> Shopping <br><br>
<input class="alignp" type="checkbox" name="interest" value="dining"> Dining <br><br>
<input class="alignp" type="checkbox" name="interest" value="dancing"> Dancing <br><br>
<input class="alignp" type="checkbox" name="interest" value="SightS"> Sightseeing <br><br><br>
<label>Discount Coupon code:</label> <input type="text" name="dis_code" value=""><br><br>
<label>Terms and Conditions<span>*</span>
<input type="radio" name="tos" id="accpeted" value="agree" checked>I agree</label>
<input type="radio" name="tos" id="unaccepted" value="disagree">I disagree
<p>Please provide any additional information below:- </p>
<textarea name="message" rows="5" cols="45" placeholder="Please type here...."></textarea><br><br>
<button class="btn-submit" id="submit" onclick="return validateForm()">Submit</button>
</div>
<script>
// JavaScript Document
function validateForm() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var dob = document.getElementById("dob").value;
//Select Box
var e = document.getElementById("package");
// Selected Item
var packages = e.options[e.selectedIndex].value;
var arrival = document.getElementById("arrival").value;
//var interest = document.getElementById("").value;
var tos = document.querySelector('input[name="tos"]:checked').value;
//var checkbox = document.getElementById("").value;;
var matches = name.match(/\d+/g);
var re = /^\d{4}([.\/-])\d{2}\1\d{2}$/;
if (!name) {
alert("Name must be filled out");
} else {
if (matches != null) {
alert("Name has a number in it!: " + name);
}
}
if (!email) {
alert("Email must be filled out");
} else {
if (validateEmail(email) == false) {
alert("Must enter a valid email: " + email);
}
}
if (!dob) {
alert("Date of Birth must not be empty");
} else {
if (!dob.match(re)) {
alert(" Dob has Invalid date format: " + dob);
}
}
if (!arrival) {
alert("Arrival Date must not be empty");
} else {
if (!arrival.match(re)) {
alert(" Dob has Invalid date format: " + arrival);
}
}
if (tos != "agree") {
alert("You must agree to the Terms of Service");
}
}
function validateEmail(email) {
return /\S+#\S+\.\S+/.test(email);
}
</script>
</body>
</html>

JavaScript Form Validation Not Returning False

If any of the form validations do not match, it is supposed to add one to a counter. At the end, if the counter is greater than zero, it is supposed to return false and not allow the form to submit.
I've written the code in Brackets. I've tried using both a hosted site and live preview to test the code, both of which result in the same issue. I've tried turning the function into a variable. I've tried different methods of taking the variables from the form. I've tried simply copying a different solution I found to this through google. Nothing seems to be working to get the validation to work as intended.
I apologize ahead of time for the wall of code.
JavaScript:
function checkAll(){
var userNameVerification = "0-9a-zA-Z"; //must include upper and lowercase so that user may use caps
var phoneNumberVerification = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/; //taken from w3resoucre for the setup of phone number verification
var checker = 0;
var userName = document.regForm.userName.value;
var password = document.regForm.passwordvalue;
var passwordVerify = document.regForm.passwordVerify.value;
var firstName = document.regForm.firstName.value;
var lastName = document.regForm.lastName.value;
var email = document.regForm.email.value;
var phoneNumber = document.regForm.phoneNumber.value;
var signUpNewsletter = document.regForm.phoneNumber.value;
//check if username is empty
if(userName == ""){
document.getElementById('errorUserName').innerHTML = "Username cannot be empty.";
checker++;
}
//make sure username uses proper characters
if(!userName.match(userNameVerification)){
document.getElementById('errorUserName').innerHTLM = "Enter only numbers and letters.";
checker++;
}
//check if password is empty or is shorter than 8 characters
if(password == "" || password.lenth < 8) {
document.getElementById('errorPassword').innerHTML = "Password should be at least 8 characters long.";
checker++;
}
//make sure confirmation of password is not shorter than 8 and is not empty
if(passwordVerify == "" || passwordVerify.lenth < 8) {
document.getElementById('errorPasswordVerify').innerHTML = "Confirmation Password should be at least 8 characters long.";
checker++;
}
//passwords match
if(password != passwordVerify){
document.getElementById('errorPasswordVerify').innerHTML = "Passwords do not match.";
checker++;
}
//check if first name is empty
if(firstName == ""){
document.getElementById('errorFirstName').innerHTML = "First name cannot be empty.";
checker++;
}
//check if last name is empty
if(lastName == ""){
document.getElementById('errorLastName').innerHTML = "Last Name cannot be empty.";
checker++;
}
//check if email is empty
if(email == ""){
document.getElementById('errorEmail').innerHTML = "Email cannot be empty.";
checker++;
}
//check that # and . are present
if(email.indexOf("#",0) < 0 || email.indexOf(".",0) < 0){
document.getElementById('errorEmail').innerHTML = "Enter a valid email address.";
checker++;
}
//check if phone number is empty
if(phoneNumber == ""){
document.getElementById('errorPhoneNumber').innerHTML = "You must enter a phone number.";
checker++;
}
//make sure phone number is in proper format
if(!phoneNumber.match(phoneNumberVerification)){
document.getElementById('errorPhoneNumber').innerHTML = "Enter a valid phone number in (XXX)XXX-XXXX format.";
checker++;
}
//make sure one of the radio buttons are clicked
if((signUpNewsletter[0].checked == false) && (signUpNewsletter[1].checked == false)){
document.getElementById('errorSignUp').innerHTML = "Please select one of the options.";
checker++;
}
//see if checker is greater than 0; if so, return false
if(checker > 0){
return false;
}
}
HTML:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Invitation Page</title>
<link rel="stylesheet" type="text/css" href="css/main.css" />
<script type="text/javascript" src="js/registration.js"></script>
</head>
<body>
<header>
<div class="top">
<a class="logo" href="index.html">CapellaVolunteers<span class="dotcom">.org</span></a>
</div>
<nav>
<ul class="topnav">
<li>Home
</li>
<li>Invitation
</li>
<li>Volunteers
</li>
<li>Gallery
</li>
<li>Registration
</li>
</ul>
</nav>
</header>
<section id="pageForm">
<form name="regForm" action="confirmation.php" method="POST">
<label for="userName">Username:</label>
<input type="text" name="userName" placeholder="Enter your Username" />
<span id="errorUserName"></span><br>
<label for="Password">Password:
</label>
<input type="password" name="password" placeholder="Enter your Password" />
<span id="errorPassword"></span><br>
<label for="passwordVerify">Verify your Password:
</label>
<input type="password" name="passwordVerify" placeholder="Enter in your Password again" />
<span id="errorPasswordVerify"></span><br>
<label for="firstName">First Name:
</label>
<input type="text" name="firstName" placeholder="Enter your First Name" />
<span id="errorFirstName"></span><br>
<label for="lastName">Last Name:
</label>
<input type="text" name="lastName" placeholder="Enter your Last Name" />
<span id="errorLastName"></span><br>
<label for="email">Email:
</label>
<input type="text" name="email" placeholder="Enter your Email Address" />
<span id="errorEmail"></span><br>
<label for="phoneNumber">Phone Number
</label>
<input type="text" name="lastName" placeholder="Enter your Phone Number" />
<span id="errorPhoneNumber"></span><br>
<label for="signUpNewsletter">Sign up for newsletter:
</label>
<input type="radio" name="signUpNewsletter" value="Yes" checked> Yes
<input type="radio" name="signUpNewsletter" value="No"> No
<span id="errorSignUp"></span><br>
<input type="submit" value="Next step" onsubmit="return checkAll();">
</form>
</section>
<footer>This events site is for IT3515 tasks.
</footer>
</body>
</html>
I expect the form to not submit when the information is not validated (for example, I try submitting an empty form, which it should not allow me to do), but it actually submits the form no matter what information is inserted into the form.
Add your onsubmit call to form instead of button, it works. Don't know about your logic, but it works. Run this code!
function checkAll(){
var condition = false;
if(condition){
alert ('All ok');
return true;
}
alert('Something wrong');
return false;
}
<section id="pageForm">
<form name="regForm" action="confirmation.php" method="POST" onsubmit="return checkAll();">
<label for="userName">Username:</label>
<input type="text" name="userName" placeholder="Enter your Username" />
<span id="errorUserName"></span><br>
<label for="Password">Password:
</label>
<input type="password" name="password" placeholder="Enter your Password" />
<span id="errorPassword"></span><br>
<label for="passwordVerify">Verify your Password:
</label>
<input type="password" name="passwordVerify" placeholder="Enter in your Password again" />
<span id="errorPasswordVerify"></span><br>
<label for="firstName">First Name:
</label>
<input type="text" name="firstName" placeholder="Enter your First Name" />
<span id="errorFirstName"></span><br>
<label for="lastName">Last Name:
</label>
<input type="text" name="lastName" placeholder="Enter your Last Name" />
<span id="errorLastName"></span><br>
<label for="email">Email:
</label>
<input type="text" name="email" placeholder="Enter your Email Address" />
<span id="errorEmail"></span><br>
<label for="phoneNumber">Phone Number
</label>
<input type="text" name="lastName" placeholder="Enter your Phone Number" />
<span id="errorPhoneNumber"></span><br>
<label for="signUpNewsletter">Sign up for newsletter:
</label>
<input type="radio" name="signUpNewsletter" value="Yes" checked> Yes
<input type="radio" name="signUpNewsletter" value="No"> No
<span id="errorSignUp"></span><br>
<input type="submit" value="Next step" >
</form>
</section>

My Jquery does not connect to my html

my jquery is not connecting and I cannot figure out why. I've been stumped on this for hours and I cannot figure it out.
this is my html code. The file name is exercise6.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Exercise 6</title>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="JS/exercise6.js"> </script>
</head>
<body>
<form id="email_form" name="email_form" action="exercise6.html" method="get">
<fieldset class="info">
<legend>Contact Information</legend>
<p>
<input type="text" name="Lname" id="name2" value="" required />
<label for="name2"> Last</label>
</p>
<p>
<input type="text" name="mailAddie" id="mail1" value="" required />
<label for="mail1"> Address</label>
</p>
<p>
<input type="text" name="City" id="city1" value="" />
<label for="city1"> City</label>
</p>
<p>
<input type="text" name="State" id="state1" value="" />
<label for="state1"> State</label>
</p>
<p>
<input type="number" name="Zip" id="zip1" value="" />
<label for="zip1"> Zip</label>
</p>
<p>
<input type="number" name="phoneNum" id="number" />
<label for="number"> Phone</label>
</p>
</fieldset>
<fieldset>
<legend>Sign up for our email list</legend>
<p>
<label for="email_address1"> Email Address</label>
<input type="text" name="email_address1" id="email_address1" value="" />
<span>*</span><br>
</p>
<p>
<label for="email_address2"> Confirm Email Address</label>
<input type="text" name="email_address2" id="email_address2" value="" />
<span>*</span><br>
</p>
<p>
<label for="first_name"> First</label>
<input type="text" name="first_name" id="first_name" value="" />
<span>*</span><br>
</p>
</fieldset>
<p>
<label> </label>
<input type="submit" value="Join Our List" id="join_list" >
</p>
</form>
</body>
</html>
and this is my javascript. The file name is exercise6.js and it is located in a file named JS. I do not know what I am doing wrong.
$(document).ready(function() {
$("#join_list").click(function() {
var emailAddress1 = $("#email_address1").val();
var emailAddress2 = $("#email_address2").val();
var isValid = true;
if (emailAddress1 == "") {
$("#email_address1").next().text("This field is required.");
isValid = false;
} else {
$("#email_address1").next().text("");
}
if (emailAddress2 == "") {
$("#email_address2").next().text("This field is required.");
isValid = false;
} else {
$("#email_address2").next().text("");
}
if ($("#first_name").val() == "") {
$("#first_name").next().text("This field is required.");
isValid = false
} else {
$("#first_name").next().text("");
}
if (isValid) {
$("#email_form").submit();
}
)};
)};
Can anyone help me?
The last two lines of exercise6.js both have a syntax error.
Change:
)};
)};
To:
});
});
To find this yourself next time, try using web development IDE like NetBeans with the help of right click with mouse to inspect in browser debug console, which would have even shown you where is this kind of error.
Your js code has some errors for close the function "});" try this
$(document).ready(function() {
$("#join_list").click(function() {
var emailAddress1 = $("#email_address1").val();
var emailAddress2 = $("#email_address2").val();
var isValid = true;
if (emailAddress1 == "") {
$("#email_address1").next().text("This field is required.");
isValid = false;
} else {
$("#email_address1").next().text("");
}
if (emailAddress2 == "") {
$("#email_address2").next().text("This field is required.");
isValid = false;
} else {
$("#email_address2").next().text("");
}
if ($("#first_name").val() == "") {
$("#first_name").next().text("This field is required.");
isValid = false
} else {
$("#first_name").next().text("");
}
if (isValid) {
$("#email_form").submit();
}
});
});

Form not validating

Can someone tell me what I'm wrong with my code? It's not validating. When I hit the submit button, nothing happens. There's no error message that shows or pop up.
Here is the html of the form
<form name="summerForm" method="post" action="signup.html">
<h2>Programs</h2>
<p>Please select the following prgrams:</p>
<select name="programs">
<option value="beginningSpanish">Beginning Spanish</option>
<option value="advancedSpanish">Advanced Spanish</option>
<option value="conversationalSpanish">Conversational Spanish</option>
<option value="advancedConversationalSpanish">Advanced Conversational Spanish</option>
<option value="spanishGrammerAndComposition">Spanish Grammar and Composition</option>
<option value="culturalTreasuresOfMexico">Cultural Treasures of Mexico</option>
</select>
<h2>Parent's Information</h2>
<label for="firstName">First Name:</label>
<input type="text" id="pFirstName" name="pFirstName"/>
<label for="middleName">Middle Name:</label>
<input type="text" id="pMiddleName" name="pMiddleName"/>
<label for="lastName">Last Name:</label>
<input type="text" id="pLastName" name="LastName"/>
<br/>
<strong>Relationship to Child:</strong><br/>
<label for="nameFather">Father</label>
<input type="radio" id="pFather" name="relationship" value="Father"/>
<label for="nameMother">Mother</label>
<input type="radio" id="pMother" name="relationship" value="Mother"/>
<label for="nameGuardian">Guardian</label>
<input type="radio" id="pGuardian" name="relationship" value="Guardian"/>
<br/>
<label for="address1">Address</label>
<input type="text" id="pAddress" name="pAddress"/><br/>
<label for="city1">City</label>
<input type="text" id="pCity" name="pCity"/>
<label for="state1">State</label>
<input type="text" id="pState" size="2" maxlength="2" name="pState"/>
<label for="zipCode1">Zip Code</label>
<input type="text" size="5" maxlength="5" id="pZipCode" name="pZipCode"/><br/>
<label for="homePhone">Home Phone</label>
<input type="text" id="pHomePhone" name="pHomePhone"/>
<label for="cellPhone">Cell Phone</label>
<input type="text" id="pCellPhone" name="pCellPhone"/><br/>
<label for="emailAddress">Email Address:</label>
<input type="text" id="pEmailAddress" name="pEmailAddress"/>
<h2>Child's Information</h2>
<label for="cFirstName">First Name:</label>
<input type="text" id="cFirstName" name="cFirstName"/>
<label for="cMiddleName">Middle Name:</label>
<input type="text" id="cMiddleName" name="cMiddleName"/>
<label for="cLastName">Last Name:</label>
<input type="text" id="cLastName" name="cLastName"/><br/>
<label for="secondName">Name the child goes by:</label>
<input type="text" id="secondName" name="secondName"/><br/>
Photo of child. (recommended format: 400x400 .jpg)<br/>
<input type="file" name="photo"/><br/>
<strong>Gender:</strong><br/>
<label for="cMale">Male</label>
<input type="radio" id="cMale" name="sex" value="Male"/>
<label for="cFemale">Female</label>
<input type="radio" id="cFemale" name="sex" value="Female"/><br/>
<label for="cDOB">Date of Birth:</label>
<input type="date" id="cDOB" size="12" maxlength="10" placeholder="MM/DD/YYYY" name="cDOB"/><br/>
<label for="cMedical">Medical Conditions:</label><br/>
<textarea id="cMedical" name="comments"> </textarea><br/>
<label for="cSDR">Special Dietary Requirements:</label><br/>
<textarea id="cSDR" name="comments"> </textarea><br/>
<p><strong>Secondary Emergency Contact</strong></p>
First Name
<input type="text" name="sFirstName"/>
Last Name
<input type="text" name="sLastName"/>
Phone Number
<input type="text" name="sPhoneNumber"/><br/>
<input type="submit" name="submit" value="Submit"/>
</form>
Here is the Jquery/Javascript
$(document.ready( function() {
var errorStatusHandle = $('.errorMessage');
var elementHandle = new Array (15);
elementHandle[0] = $('[name="pFirstName"]');
elementHandle[1] = $('[name="pLastName"]');
elementHandle[2] = $('[name="pAddress"]');
elementHandle[3] = $('[name="pCity"]');
elementHandle[4] = $('[name="pState"]');
elementHandle[5] = $('[name="pZipCode"]');
elementHandle[6] = $('[name="pCellPhone"]');
elementHandle[7] = $('[name="pEmailAddress"]');
elementHandle[8] = $('[name="cFirstName"]');
elementHandle[9] = $('[name="cLastName"]');
elementHandle[10] = $('[name="secondName"]');
elementHandle[11] = $('[name="cDOB"]');
elementHandle[12] = $('[name="sFirstName"]');
elementHandle[13] = $('[name="sLastName"]');
elementHandle[14] = $('[name="sPhoneNumber"]');
function isValidData() {
if(isEmpty(elementHandle[0].val())) {
elementHandle[0].addClass("error");
errorStatusHandle.text("Please enter your first name.");
elementHandle[0].focus();
return false;
}
if(isEmpty(elementHandle[1].val())) {
elementHandle[1].addClass("error");
errorStatusHandle.text("Please enter your last name.");
elementHandle[1].focus();
return false;
}
if(isEmpty(elementHandle[2].val())) {
elementHandle[2].addClass("error");
errorStatusHandle.text("Please enter your address.");
elementHandle[2].focus();
return false;
}
if(isEmpty(elementHandle[3].val())) {
elementHandle[3].addClass("error");
errorStatusHandle.text("Please enter your city.");
elementHandle[3].focus();
return false;
}
if(isEmpty(elementHandle[4].val())) {
elementHandle[4].addClass("error");
errorStatusHandle.text("Please enter your state.");
elementHandle[4].focus();
return false;
}
if(!isValidState(elementHandle[4].val())) {
elementHandle[4].addClass("error");
errorStatusHandle.text("The state appears to be invalid, "+
"please use the two letter state abbreviation");
elementHandle[4].focus();
return false;
}
if(isEmpty(elementHandle[5].val())) {
elementHandle[5].addClass("error");
errorStatusHandle.text("Please enter your zip code.");
elementHandle[5].focus();
return false;
}
if(isEmpty(elementHandle[6].val())) {
elementHandle[6].addClass("error");
errorStatusHandle.text("Please enter your cell phone number.");
elementHandle[6].focus();
return false;
}
if(isEmpty(elementHandle[7].val())) {
elementHandle[7].addClass("error");
errorStatusHandle.text("Please enter your email adddress.");
elementHandle[7].focus();
return false;
}
if(isEmpty(elementHandle[8].val())) {
elementHandle[8].addClass("error");
errorStatusHandle.text("Please enter your child's first name.");
elementHandle[8].focus();
return false;
}
if(isEmpty(elementHandle[9].val())) {
elementHandle[9].addClass("error");
errorStatusHandle.text("Please enter your child's last name.");
elementHandle[9].focus();
return false;
}
if(isEmpty(elementHandle[10].val())) {
elementHandle[10].addClass("error");
errorStatusHandle.text("Please enter your child's name that he/she wish to go by.");
elementHandle[10].focus();
return false;
}
if(isEmpty(elementHandle[11].val())) {
elementHandle[11].addClass("error");
errorStatusHandle.text("Please enter your child's date of birth.");
elementHandle[11].focus();
return false;
}
if(isEmpty(elementHandle[12].val())) {
elementHandle[12].addClass("error");
errorStatusHandle.text("Please enter your emergency contact first name.");
elementHandle[12].focus();
return false;
}
if(isEmpty(elementHandle[13].val())) {
elementHandle[13].addClass("error");
errorStatusHandle.text("Please enter your emergency contact last name.");
elementHandle[13].focus();
return false;
}
if(isEmpty(elementHandle[14].val())) {
elementHandle[14].addClass("error");
errorStatusHandle.text("Please enter your emergency contact phone number.");
elementHandle[14].focus();
return false;
}
return true;
}
elementHandle[0].focus();
$(':submit').on('click', function() {
for(var i=0; i < 10; i++)
elementHandle[i].removeClass("error");
errorStatusHandle.text("");
return isValidData();
});
}));
isEmpty function is not defined
isValidState function is not defined
instead of:
$(':submit').on('click', function() {
use:
$('form').submit(function() {
Okay, let's fix this
For starters, you didn't include the isEmpty() function. Therefore, when the code you included was run, your isValidData() function caused an error, which stopped the form from returning false. isValidState() is also undefined, but I'm not going to write that for you
Secondly, I'd suggest instead of using the click event on :submit, use the submit event on form[name=summerForm]. First it narrows your validity checking to just the form you want, and secondly there are more ways to submit a form than just clicking the button. This will catch those.
Thirdly, and most importantly, you didn't include an error message element. The reason you're not seeing anything, is because while you set a .text to .errorMessage, .errorMessage doesn't exist. Refer to this fiddle
http://jsfiddle.net/kaexgob8/
HTML:
<form name="summerForm" method="post" action="signup.html">
<h2>Programs</h2>
<p>Please select the following prgrams:</p>
<select name="programs">
<option value="beginningSpanish">Beginning Spanish</option>
<option value="advancedSpanish">Advanced Spanish</option>
<option value="conversationalSpanish">Conversational Spanish</option>
<option value="advancedConversationalSpanish">Advanced Conversational Spanish</option>
<option value="spanishGrammerAndComposition">Spanish Grammar and Composition</option>
<option value="culturalTreasuresOfMexico">Cultural Treasures of Mexico</option>
</select>
<h2>Parent's Information</h2>
<label for="firstName">First Name:</label>
<input type="text" id="pFirstName" name="pFirstName"/>
<label for="middleName">Middle Name:</label>
<input type="text" id="pMiddleName" name="pMiddleName"/>
<label for="lastName">Last Name:</label>
<input type="text" id="pLastName" name="LastName"/>
<br/>
<strong>Relationship to Child:</strong><br/>
<label for="nameFather">Father</label>
<input type="radio" id="pFather" name="relationship" value="Father"/>
<label for="nameMother">Mother</label>
<input type="radio" id="pMother" name="relationship" value="Mother"/>
<label for="nameGuardian">Guardian</label>
<input type="radio" id="pGuardian" name="relationship" value="Guardian"/>
<br/>
<label for="address1">Address</label>
<input type="text" id="pAddress" name="pAddress"/><br/>
<label for="city1">City</label>
<input type="text" id="pCity" name="pCity"/>
<label for="state1">State</label>
<input type="text" id="pState" size="2" maxlength="2" name="pState"/>
<label for="zipCode1">Zip Code</label>
<input type="text" size="5" maxlength="5" id="pZipCode" name="pZipCode"/><br/>
<label for="homePhone">Home Phone</label>
<input type="text" id="pHomePhone" name="pHomePhone"/>
<label for="cellPhone">Cell Phone</label>
<input type="text" id="pCellPhone" name="pCellPhone"/><br/>
<label for="emailAddress">Email Address:</label>
<input type="text" id="pEmailAddress" name="pEmailAddress"/>
<h2>Child's Information</h2>
<label for="cFirstName">First Name:</label>
<input type="text" id="cFirstName" name="cFirstName"/>
<label for="cMiddleName">Middle Name:</label>
<input type="text" id="cMiddleName" name="cMiddleName"/>
<label for="cLastName">Last Name:</label>
<input type="text" id="cLastName" name="cLastName"/><br/>
<label for="secondName">Name the child goes by:</label>
<input type="text" id="secondName" name="secondName"/><br/>
Photo of child. (recommended format: 400x400 .jpg)<br/>
<input type="file" name="photo"/><br/>
<strong>Gender:</strong><br/>
<label for="cMale">Male</label>
<input type="radio" id="cMale" name="sex" value="Male"/>
<label for="cFemale">Female</label>
<input type="radio" id="cFemale" name="sex" value="Female"/><br/>
<label for="cDOB">Date of Birth:</label>
<input type="date" id="cDOB" size="12" maxlength="10" placeholder="MM/DD/YYYY" name="cDOB"/><br/>
<label for="cMedical">Medical Conditions:</label><br/>
<textarea id="cMedical" name="comments"> </textarea><br/>
<label for="cSDR">Special Dietary Requirements:</label><br/>
<textarea id="cSDR" name="comments"> </textarea><br/>
<p><strong>Secondary Emergency Contact</strong></p>
First Name
<input type="text" name="sFirstName"/>
Last Name
<input type="text" name="sLastName"/>
Phone Number
<input type="text" name="sPhoneNumber"/><br/>
<input type="submit" name="submit" value="Submit"/>
<div class='errorMessage' ></div>
</form>
JS:
var errorStatusHandle = $('.errorMessage');
var elementHandle = new Array (15);
elementHandle[0] = $('[name="pFirstName"]');
elementHandle[1] = $('[name="pLastName"]');
elementHandle[2] = $('[name="pAddress"]');
elementHandle[3] = $('[name="pCity"]');
elementHandle[4] = $('[name="pState"]');
elementHandle[5] = $('[name="pZipCode"]');
elementHandle[6] = $('[name="pCellPhone"]');
elementHandle[7] = $('[name="pEmailAddress"]');
elementHandle[8] = $('[name="cFirstName"]');
elementHandle[9] = $('[name="cLastName"]');
elementHandle[10] = $('[name="secondName"]');
elementHandle[11] = $('[name="cDOB"]');
elementHandle[12] = $('[name="sFirstName"]');
elementHandle[13] = $('[name="sLastName"]');
elementHandle[14] = $('[name="sPhoneNumber"]');
function isEmpty(val)
{
if(val == '' || val === null || val === undefined)
return true;
return false;
}
function isValidData()
{
if(isEmpty(elementHandle[0].val())) {
elementHandle[0].addClass("error");
errorStatusHandle.text("Please enter your first name.");
elementHandle[0].focus();
return false;
}
if(isEmpty(elementHandle[1].val())) {
elementHandle[1].addClass("error");
errorStatusHandle.text("Please enter your last name.");
elementHandle[1].focus();
return false;
}
if(isEmpty(elementHandle[2].val())) {
elementHandle[2].addClass("error");
errorStatusHandle.text("Please enter your address.");
elementHandle[2].focus();
return false;
}
if(isEmpty(elementHandle[3].val())) {
elementHandle[3].addClass("error");
errorStatusHandle.text("Please enter your city.");
elementHandle[3].focus();
return false;
}
if(isEmpty(elementHandle[4].val())) {
elementHandle[4].addClass("error");
errorStatusHandle.text("Please enter your state.");
elementHandle[4].focus();
return false;
}
if(!isValidState(elementHandle[4].val())) {
elementHandle[4].addClass("error");
errorStatusHandle.text("The state appears to be invalid, "+
"please use the two letter state abbreviation");
elementHandle[4].focus();
return false;
}
if(isEmpty(elementHandle[5].val())) {
elementHandle[5].addClass("error");
errorStatusHandle.text("Please enter your zip code.");
elementHandle[5].focus();
return false;
}
if(isEmpty(elementHandle[6].val())) {
elementHandle[6].addClass("error");
errorStatusHandle.text("Please enter your cell phone number.");
elementHandle[6].focus();
return false;
}
if(isEmpty(elementHandle[7].val())) {
elementHandle[7].addClass("error");
errorStatusHandle.text("Please enter your email adddress.");
elementHandle[7].focus();
return false;
}
if(isEmpty(elementHandle[8].val())) {
elementHandle[8].addClass("error");
errorStatusHandle.text("Please enter your child's first name.");
elementHandle[8].focus();
return false;
}
if(isEmpty(elementHandle[9].val())) {
elementHandle[9].addClass("error");
errorStatusHandle.text("Please enter your child's last name.");
elementHandle[9].focus();
return false;
}
if(isEmpty(elementHandle[10].val())) {
elementHandle[10].addClass("error");
errorStatusHandle.text("Please enter your child's name that he/she wish to go by.");
elementHandle[10].focus();
return false;
}
if(isEmpty(elementHandle[11].val())) {
elementHandle[11].addClass("error");
errorStatusHandle.text("Please enter your child's date of birth.");
elementHandle[11].focus();
return false;
}
if(isEmpty(elementHandle[12].val())) {
elementHandle[12].addClass("error");
errorStatusHandle.text("Please enter your emergency contact first name.");
elementHandle[12].focus();
return false;
}
if(isEmpty(elementHandle[13].val())) {
elementHandle[13].addClass("error");
errorStatusHandle.text("Please enter your emergency contact last name.");
elementHandle[13].focus();
return false;
}
if(isEmpty(elementHandle[14].val())) {
elementHandle[14].addClass("error");
errorStatusHandle.text("Please enter your emergency contact phone number.");
elementHandle[14].focus();
return false;
}
return true;
}
$('form [name=summerForm]').on('submit', function()
{
for(var i=0; i < 10; i++)
elementHandle[i].removeClass("error");
errorStatusHandle.text("");
var valid = isValidData();
return valid;
});
.errorMessage {
color: red;
}
Try to use jQuery Validation.
<form name="summerForm" id="summerFormID" method="post" action="signup.html">
<select name="programs">
// options
</select>
<input type="text" id="pFirstName" name="pFirstName"/>
<label for="middleName">Middle Name:</label>
<input type="text" id="pMiddleName" name="pMiddleName"/>
<label for="lastName">Last Name:</label>
<input type="text" id="pLastName" name="LastName"/>
<br/>
. . .
<input type="submit" name="submit" value="Submit"/>
</form>
jQuery/js:
jQuery(document).ready(function(){
$('#summerFormID').validate({
rules: {
programs:{
required: true
},
pFirstName:{
required: true
},
pMiddleName:{
required: true
},
pLastName:{
required: true
}
},
messages: {
programs:{
required: "please select a program!"
},
pFirstName:{
required: "FirstName required!"
},
pMiddleName:{
required: "MiddleName required!"
},
pLastName:{
required: "Last Name Required!"
}
},
submitHandler: function(form){
form.submit();
}
});
});
*You can also try other validation rules or make your own rule. See jQuery Validation page. And don't forget to add the plugin in your program/project.

trouble validating various inputs with jQuery

for a class project I have to build a website for a pet store, featuring a pet grooming service. This involves a form, php and a mysql server on my localhost. I have been unable to correctly validate this form via a jQuery validator plugin for some unknown (to me) reason.
I've had no luck via regular jQuery code beyond getting the form to not submit blank input values. So as it is, anybody can put 'sadklfhsdk' in any of the fields (except for email, unless it has a '#') and it will validate and submit to the server.
So after I going through a couple of tutorials this is what I have so far:
The HTML:
<body>
<div id="h2Groom"><h2>Grooming Request Form</h2></div>
<form id="groom_form" method="post" action="insertPS.php">
<div id="result"></div>
<label for="firstName"><span>First Name:</span>
<input type="text" name="firstName" id="firstName" placeholder="Enter Your First Name" class="required"/>
</label>
<label for="lastName"><span>Last Name:</span>
<input type="text" name="lastName" id="lastName" placeholder="Enter Your Last Name" class="required"/>
</label>
<label for="email"><span>Email Address:</span>
<span id="error"></span>
<input type="email" name="email" id="email" placeholder="Enter a Email"/>
</label>
<label for="phone"><span>Phone Number:</span>
<span id="error"></span>
<input type="text" name="phone" id="phone" placeholder="Enter a phone number" class="required"/>
</label>
<label for="address"><span>Address:</span>
<input type="text" name="address" id="address" placeholder="Enter your address" class="required"/>
</label>
<label for="city"><span>City:</span>
<input type="text" name="city" id="city" placeholder="Enter your city" />
</label>
<label for="state"><span>State:</span>
<input type="text" name="state" id="state" placeholder="Enter your state" class="required"/>
</label>
<label for="zipcode"><span>Zipcode:</span>
<input type="text" name="zipcode" id="zipcode" placeholder="Enter your zipcode" class="required"/>
</label>
<label for="petType"><span>Type of Pet:</span>
<ul>
<li><label><input name="petType" type="radio" value="dog" id="dog">Dog</label></li>
<li><label><input name="petType" type="radio" value="cat" id="cat">Cat</label></li>
<li><label><input name="petType" type="radio" value="bird" id="bird">Bird</label></li>
</ul>
</label>
<select id="breed" name="breed">
<option value="0">--Please Choose Dog Breed--</option>
<option value="AlaskanMal">Alaskan Malamute</option>
<option value="Bichon">Bichon Frise</option>
<option value="WelshCorgi">Corgi, Welsh</option>
<option value="Dalmation">Dalmation</option>
<option value="EnglishToySpan">English Toy Spaniel</option>
<option value="FrenchBull">French Bull Dog</option>
<option value="Greyhound">Greyhound</option>
<option value="Papillon">Papillon</option>
<option value="Rottweiler">Rottweiler</option>
<option value="YorkshireTerr">Yorkshire Terrier</option>
</select>
<label for="neut"><span>Check box if your pet has been neutered/spayed (leave unchecked if not).</span></label>
<ul>
<label>
<li><input type="checkbox" name="neut" id="neut" />Yes</li></label>
</ul>
<br />
<br />
<br />
<label for="petname"><span>Pet Name:</span>
<input type="text" name="petname" id="petname" placeholder="Enter your pet's name" class="required" />
</label>
<label for="petBday"><span>Pet's Birthday:</span>
<input type="date" id="petBday" name="petBday"/>
</label>
<span> </span>
<input type="submit" id="submitBttn" value="Submit" /><input type="reset" id="resetBttn" value="Reset" />
</form>
</body>
The jQUERY (except the script to send values to server, see jsfiddle link):
$(document).ready(function() {
$('input[name=petType]').click(function() {
if(this.id=='dog') {
$('#breed').show('slow');
}
else {
$('#breed').hide('slow');
}
});
$('input[name=phone]').blur(function() {
if (validatePhone('phone')) {
$('#error').html('Valid');
$('#error').css('color', 'green');
}
else {
$('#error').html('Invalid');
$('#error').css('color', 'red');
}
});
$('input[name=email]').blur(function() {
if (validateEmail('email')) {
$('#error').html('Valid');
$('#error').css('color', 'green');
}
else {
$('#error').html('Invalid');
$('#error').css('color', 'red');
}
});
$("#submitBttn").click(function() {
//get input field values
var user_firstName = $('input[name=firstName]').val();
var user_lastName = $('input[name=lastName]').val();
var user_email = $('input[name=email]').val();
var user_address = $('input[name=address]').val();
var user_phone = $('input[name=phone]').val();
var user_city = $('input[name=city]').val();
var user_state = $('input[name=state]').val();
var user_zipcode = $('input[name=zipcode]').val();
var user_petname = $('input[name=petname]').val();
var checked_radio = $('input:radio[name=petType]').is(':checked');
var user_neut = $('input:checkbox[name=neut]').is(':checked');
var user_breed = $('input:select[name=breed]').is(':selected');
var txtVal = $('#petBday').val();
if(isDate(txtVal))
alert('Valid Date');
else
alert('Invalid Date');
var proceed = true;
//Validation functions, executed when user hits "submit"
function validatePhone(phone) {
var a = document.getElementById(phone).value;
var filter = /^[0-9-+]+$/;
if (filter.text(phone)) {
return true;
}
else {
return false;
}
}
function validateEmail(email) {
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(email)) {
return true;
}
else {
return false;
}
}
function isDate(txtDate)
{
var currVal = txtDate;
if(currVal == '')
return false;
//declare regex
var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
var dtArray = currVal.match(rxDatePattern); //is the format ok?
if(dtArray ==null)
return false;
//checks for mm/dd/yyyy format
dtMonth = dtArray[1];
dtDay = dtArray[3];
dtYear = dtArray[5];
if(dtMonth < 1 || dtMonth > 12)
return false;
else if (dtDay < 1 || dtDay > 31)
return false;
else if ((dtMonth==4 || dtMonth==6 || dtMonth==9 || dtMonth==11) && dtDay ==31)
return false;
else if (dtMonth == 2)
{
var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
if(dtDay > 29 || (dtDay ==29 && !isleap))
return false;
}
return true;
}
EDIT: corrected if(filter.text()) to if(filter.test(phone)). None of my java validation code works.
validatePhone: filter.text should be spelled test

Categories

Resources