Javascript validation is not working in html registration form - javascript

I am using php mysql for user registration. I have added javascript validation to check if any field is blank or not. But the form validation is not working. the form is
<?php
include("header.php");
include ("includes/mainmenu.php");
?>
<!--Javasript Validation File Import -->
<script type="text/javascript" src="js/validation.js"></script>
<script type="text/javascript" src="js/formreg.js"></script>
<script type="text/javascript" language="JavaScript">
function HidePart(d) { document.getElementById(d).style.display = "none"; }
function ShowPart(d) { document.getElementById(d).style.display = "block"; }
function CheckboxChecked(b,d)
{
if(b) { ShowPart(d); }
else { HidePart(d); }
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!--<link rel="stylesheet" type="text/css" href="styles/styles.css" />-->
<link href="styles/form.css" rel="stylesheet" type="text/css">
<link href="styles/structure.css" rel="stylesheet">
<link href="styles/bootstrap.css" rel="stylesheet">
</head>
<body onLoad="document.registration.userid.focus();">
<br>
<div id="container" class="ltr">
<header id="header" class="info">
<h2>User Registration</h2>
</header>
<form action="insert.php" method="post" name="regForm" onSubmit="return valide()">
<ul>
<li id="foli0" class="notranslate">
<label class="desc" id="title0" for="Field0">Name</label>
<span><input id="fname" type="text" name="fname" class="field text1 fn" size="50"/></span><span>Please Enter Your full Name</span>
</li>
<li id="foli0" class="notranslate">
<label class="desc" id="title0" for="Field0">Username</label>
<span><input id="Field0" type="text" name="usernamename" class="field text1 fn" size="50" /></span>
</li>
<li id="foli0" class="notranslate">
<label class="desc" id="title0" for="group">Educational Background</label></td>
<span><select id="Field0" class="field text1 fn" name="background" size="0">
<option selected="0" value="">select your Background</option>
<option value="Science">Science</option>
<option value="Humanities">Humanities</option>
<option value="Commerce">Commerce</option>
</select></span><span>Enter your HSC Background</span>
</li>
<li id="foli0" class="notranslate">
<label class="desc" id="title0" for="Field0">Date of Birth</label>
<span><input id="Field0" type="date" name="birth" class="field text1 fn" size="50"/></span><span>Enter your date of Birth</span>
</li>
<li id="foli0" class="notranslate">
<label class="desc" id="title0" for="Field0">Password</label>
<span><input id="Field0" type="password" name="password" class="field text1 fn" size="50" /></span><span>Enter your password</span>
</li>
<li id="foli0" class="notranslate">
<label class="desc" id="title0" for="Field0">Password</label>
<span><input id="Field0" type="password" name="conpassword" class="field text1 fn" size="50" /></span><span>Enter your password again</span>
</li>
<li id="foli0" class="notranslate">
<label class="desc" id="title0" for="Field0">Email</label>
<span><input id="Field0" type="text" name="email" class="field text1 fn" size="50" /></span><span>Enter a valid email address</span>
</li>
<li class="buttons ">
<div>
<input id="submit" name="submit" class="btn" type="submit" value="Complete Registration"/></div>
</li>
</ul>
</form>
</div>
<?php
include("includes/footer.php");
?>
and the validation javascript code is
function valide()
{
var fname=document.forms["regForm"]["fname"].value;
var username=document.forms["regForm"]["username"].value;
var subject = document.forms["regForm"]["background"].value;
var password=document.forms["regForm"]["password"].value;
var conpassword=document.forms["regForm"]["conpassword"].value;
var email=document.forms["regForm"]["email"].value;
var atpos=email.indexOf("#");
var dotpos=email.lastIndexOf(".");
if (fname==null || fname=="" || fname.length<7)
{
alert("Please provide Your full name");
return false;
}
else if (username==null || username=="")
{
if(username.length<6)
{
alert("Username must contains atleast 6 charecters");
}
else
alert("Please provide a username");
return false;
}
else if(subject==null || subject == "")
{
alert("Enter Background");
return false;
}
else if (password==null || password=="")
{
if(password.length<8)
{
alert("Password must contain atleast 8 charecters");
}
else
alert("Please insert your password");
return false;
}
else if (conpassword != password)
{
alert("Confirm password doesn't match");
return false;
}
else if (email==null || email=="")
{
alert("Email must be filled out.");
return false;
}
else if (atpos <1 || dotpos <atpos+2 || dotpos + 2 >= email.length)
{
alert("Not a valid e-mail address");
return false;
}
}
Please help me.

Lets have a look at your function valide()
It has some mistakes and it does not return true when everything is ok...
Since it does not return true, form is not submitted...
Here is a corrected version:
function valide(){
var fname=document.forms["regForm"]["fname"].value;
var username=document.forms["regForm"]["username"].value;
var subject = document.forms["regForm"]["background"].value;
var password=document.forms["regForm"]["password"].value;
var conpassword=document.forms["regForm"]["conpassword"].value;
var email=document.forms["regForm"]["email"].value;
var atpos=email.indexOf("#");
var dotpos=email.lastIndexOf(".");
// Let me warn you:
// There are many many people with names less than 7 characters
if (fname==null || fname=="" || fname.length<7) {
alert("Please provide Your full name");
return false;
} // if returned so else is not required
if (username==null || username==""){
if(username.length<6){
alert("Username must contains atleast 6 charecters");
} else
alert("Please provide a username");
return false;
} // if returned so else is not required
if(subject==null || subject == ""){
alert("Enter Background");
return false;
} // if returned so else is not required
if (password == null || password==""){
// length = 0 or password is null here so:
// if(password.length<8) is unnecessary
if(password == ""){
alert("Password must contain at least 8 charecters");
} else
alert("Please insert your password");
return false;
} // if returned so else is not required
if (conpassword != password){
alert("Confirm password doesn't match");
return false;
} // if returned so else is not required
if (email==null || email==""){
alert("Email must be filled out.");
return false;
} // if returned so else is not required
if (atpos <1 || (dotpos <atpos+2) || (dotpos + 2 >= email.length)){
alert("Not a valid e-mail address");
return false;
} // if returned no else needed.
// and now this function should return:
return(true);
}

Related

how to get external form validation to work with jQuery

Okay, I'm trying to get a contact form to work and it is, sort of. The data is passing through, but I can't get the jQuery to work. If I type in two different email addresses it doesn't catch it. Here is the relevant code I used:
HTML
<aside>
<form action="sendmail.php" method="post" name="contact_form" id="contact_form">
<fieldset>
<legend>sign up now!</legend><br>
<p>Sign up for my email list and get a free mini coloring book!</p><br>
<img src="Images/minicoloirngbook.jpg" alt="mini coloring book"><br>
<label for="name"> Name:</label>
<input type="text"name="name" id="name" required><span>*</span><br>
<label for="email">Email Address:</label>
<input type="email" name="email" id="email" required><span>*</span><br>
<label for="verify">Verify Email:</label>
<input type="email" name="verify" id="verify" required> <span>*</span><br>
<div id="buttons">
<input type="submit" id="submit" value="Sign Up">
</div>
</fieldset>
</form>
</aside>
and here is the Javascript:
$("#contact_form").submit(event => {
let isValid = true;
// validate the first name entry
const name = $("#name").val().trim();
if (name == "") {
$("#name").next().text("This field is required.");
isValid = false;
} else {
$("#name").next().text("");
}
$("#name").val(name);
// validate the email entry with a regular expression
const emailPattern = /\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
const email = $("#email").val().trim();
if (email == "") {
$("#email").next().text("This field is required.");
isValid = false;
} else if ( !emailPattern.test(email) ) {
$("#email").next().text("Must be a valid email address.");
isValid = false;
} else {
$("#email").next().text("");
}
$("#email").val(email);
// validate the verify entry
const verify = $("#verify").val().trim();
if (verify == "") {
$("#verify").next().text("This field is required.");
isValid = false;
} else if (verify !== email) {
$("#verify").next().text("Must match first email entry.");
isValid = false;
} else {
$("#verify").next().text("");
}
$("#verify").val(verify);
// prevent the submission of the form if any entries are invalid
if (isValid == false) {
event.preventDefault();
}
}),
I think that the answer is probably something really simple that I can't see and would appreciate your help in figuring it out.
This should do it. Here is the jsfiddle if you like to play with the code: https://jsfiddle.net/bogatyr77/xk6ez3aq/7/
$("form").submit(function(e) {
var name = $("#a").val();
if (name == "") {
$("#nameerror").text("This field is required.");
alert('false');
} else {
alert('true');
$("#nameerror").remove();
}
//email1
var emailPattern = /\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
const email = $("#b").val();
if (email == "") {
$("#email1error").text("This field is required.");
isValid = false;
} else if (!emailPattern.test(email)) {
$("#email1error").text("Must be a valid email address.");
isValid = false;
} else {
$("#email1error").remove();
}
//eamil 2
var verify = $("#c").val();
if (verify == "") {
$("#email2error").text("This field is required.");
isValid = false;
} else if (verify !== email) {
$("#email2error").text("Must match first email entry.");
isValid = false;
} else {
$("#email2error").remove();
}
if (isValid == false) {
event.preventDefault();
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="javascript:alert('ok')">
<label for="name"> Name:</label>
<input type="text" name="name" id="a"><span>*</span>
<div id="nameerror"></div><br>
<label for="email">Email Address:</label>
<input type="text" name="email" id="b"><span>*</span>
<div id="email1error"></div><br>
<label for="verify">Verify Email:</label>
<input type="text" name="verify" id="c"> <span>*</span>
<div id="email2error"></div><br>
<input type="submit" value="submit" />
</form>
<div></div>

javascript form validation for empty field and wrong input

this program runs correctly.. my task is, when name field left empty then (please enter your name )this error will be generated and when i type wrong input(like numbers)then (only alphabets and white space are allowed)this error message has to be generate. how can i do this.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Validation tutorial</title>
<script>
function validateName(x){
// Validation rule
var re = /[A-Za-z -']$/;
// Check input
if(re.test(document.getElementById(x).value)){
// Style green
document.getElementById(x).style.borderColor ='#3BFF3B';
// Hide error prompt
document.getElementById(x + 'Error').style.display = "none";
return true;
}else{
// Style red
document.getElementById(x).style.borderColor ='#FF0000';
// Show error prompt
document.getElementById(x + 'Error').style.display = "block";
return false;
}
}
// Validate email
function validateEmail(email){
var re = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(re.test(email)){
document.getElementById('email').style.borderColor ='#3BFF3B';
document.getElementById('emailError').style.display = "none";
return true;
}else{
document.getElementById('email').style.borderColor ='#FF0000';
return false;
}
}
// Validate Select boxes
function validateSelect(x){
if(document.getElementById(x).selectedIndex !== 0){
document.getElementById(x).style.borderColor ='#3BFF3B';
document.getElementById(x + 'Error').style.display = "none";
return true;
}else{
document.getElementById(x).style.borderColor ='#FF0000';
return false;
}
}
function validateRadio(x){
if(document.getElementById(x).checked){
return true;
}else{
return false;
}
}
function validateCheckbox(x){
if(document.getElementById(x).checked){
return true;
}
return false;
}
function validateForm(){
// Set error catcher
var error = 0;
// Check name
if(!validateName('name')){
document.getElementById('nameError').style.display = "block";
error++;
}
// Validate email
if(!validateEmail(document.getElementById('email').value)){
document.getElementById('emailError').style.display = "block";
error++;
}
// Validate animal dropdown box
if(!validateSelect('subject')){
document.getElementById('subjectError').style.display = "block";
error++;
}
// Validate Radio
if(validateRadio('male')){
}else if(validateRadio('female')){
}else{
document.getElementById('genderError').style.display = "block";
error++;
}
// Don't submit form if there are errors
if(error > 0){
return false;
}
}
</script>
</head>
<body>
<form action="" onsubmit="return validateForm()">
<label for="name">Name</label>
<input type="text" name="name" id="name" onblur="validateName(name)" />
<span id="nameError" style="display: none;">only alphabates and white space are allowed</span>
<br><br>
<label for="email">Email</label>
<input type="text" name="email" id="email" onblur="validateEmail(value)" />
<span id="emailError" style="display: none;">You must enter a valid email address</span>
<br><br>
<label for="hand">Gender</label>
<ul>
<li>
<input type="radio" name="gender" id="male" value="male" onblur="validateRadio(id)" />
<label for="left">male</label>
</li>
<li>
<input type="radio" name="gender" id="female" value="female" onblur="validateRadio(id)" />
<label for="right">female</label>
</li>
</ul>
<span class="validateError" id="genderError" style="display: none;">Please select gender</span>
<br><br>
<label for="subject">Favourite Subject</label>
<select name="subject" id="subject" onblur="validateSelect(name)">
<option value="">SUBJECTS</option>
<option value="php">PHP</option>
<option value="java">JAVA</option>
<option value="sql">SQL</option>
</select>
<span class="validateError" id="subjectError" style="display: none;">You must select your favourite subject</span>
<br><br>
<input type="submit" id="submit" name="submit" value="Submit" />
</form>
</body>
</html>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Validation tutorial</title>
<script>
function validateName(x){
// Validation rule
var re = /[A-Za-z -']$/;
// Check input
if(re.test(document.getElementById(x).value)){
// Style green
document.getElementById(x).style.borderColor ='#3BFF3B';
// Hide error prompt
document.getElementById(x + 'Error').style.display = "none";
return true;
}else if(document.getElementById(x).value === ''){
//This is for an empty string or if name was not entered.
// Style red
document.getElementById(x).style.borderColor ='#FF0000';
// Show error prompt
document.getElementById(x + 'Error2').style.display = "block";
return false;
}else{
// Style red
document.getElementById(x).style.borderColor ='#FF0000';
// Show error prompt
document.getElementById(x + 'Error').style.display = "block";
return false;
}
}
// Validate email
function validateEmail(email){
var re = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(re.test(email)){
document.getElementById('email').style.borderColor ='#3BFF3B';
document.getElementById('emailError').style.display = "none";
return true;
}else{
document.getElementById('email').style.borderColor ='#FF0000';
return false;
}
}
// Validate Select boxes
function validateSelect(x){
if(document.getElementById(x).selectedIndex !== 0){
document.getElementById(x).style.borderColor ='#3BFF3B';
document.getElementById(x + 'Error').style.display = "none";
return true;
}else{
document.getElementById(x).style.borderColor ='#FF0000';
return false;
}
}
function validateRadio(x){
if(document.getElementById(x).checked){
return true;
}else{
return false;
}
}
function validateCheckbox(x){
if(document.getElementById(x).checked){
return true;
}
return false;
}
function validateForm(){
// Set error catcher
var error = 0;
// Check name
if(!validateName('name')){
document.getElementById('nameError').style.display = "block";
error++;
}
// Validate email
if(!validateEmail(document.getElementById('email').value)){
document.getElementById('emailError').style.display = "block";
error++;
}
// Validate animal dropdown box
if(!validateSelect('subject')){
document.getElementById('subjectError').style.display = "block";
error++;
}
// Validate Radio
if(validateRadio('male')){
}else if(validateRadio('female')){
}else{
document.getElementById('genderError').style.display = "block";
error++;
}
// Don't submit form if there are errors
if(error > 0){
return false;
}
}
</script>
</head>
<body>
<form action="" onsubmit="return validateForm()">
<label for="name">Name</label>
<input type="text" name="name" id="name" onblur="validateName(name)" />
<span id="nameError" style="display: none;">only alphabates and white space are allowed</span>
<span id="nameError2" style="display: none;">please enter a name</span>
<br><br>
<label for="email">Email</label>
<input type="text" name="email" id="email" onblur="validateEmail(value)" />
<span id="emailError" style="display: none;">You must enter a valid email address</span>
<br><br>
<label for="hand">Gender</label>
<ul>
<li>
<input type="radio" name="gender" id="male" value="male" onblur="validateRadio(id)" />
<label for="left">male</label>
</li>
<li>
<input type="radio" name="gender" id="female" value="female" onblur="validateRadio(id)" />
<label for="right">female</label>
</li>
</ul>
<span class="validateError" id="genderError" style="display: none;">Please select gender</span>
<br><br>
<label for="subject">Favourite Subject</label>
<select name="subject" id="subject" onblur="validateSelect(name)">
<option value="">SUBJECTS</option>
<option value="php">PHP</option>
<option value="java">JAVA</option>
<option value="sql">SQL</option>
</select>
<span class="validateError" id="subjectError" style="display: none;">You must select your favourite subject</span>
<br><br>
<input type="submit" id="submit" name="submit" value="Submit" />
</form>
</body>
</html>
There are much better ways to do this. This is not an elegant way. I see this code is from an example or tutorial. Please check other tutorials on this subject, as this is just a quick way of implementing what you want.

Onclick Validation not working

I've been working on this assignment for the longest while. My form validations weren't working previously but then I found out what the error was & everything was working perfectly.
Later on, I had made some changes to the code then deleted those changes and now the validations aren't working again & I can't seem to find what the problem is this time.
Below is my unfinished code:
function validateEmail() {
var email = document.getElementById('email').value;
if( email==null || email=="")
{
alert("Please input an email address");
}
}
function validateFName() {
var firstname = document.getElementById('firstname').value;
if( firstname==null || firstname=="")
{
alert("Please input a last name");
return false;
}
}
function validateLName() {
var lastname = document.getElementById('lastname').value;
if( lastname==null || lastname=="")
{
alert("Please input a last name");
}
}
function validateGender() {
var gender = document.getElementById('gender').value;
if( gender==null || gender=="")
{
alert("Please select a gender");
}
}
function validateDate() {
var date = document.getElementById('date').value;
if( date==null || date=="")
{
alert("Please select a date");
}
}
function validateVName() {
var vname = document.getElementById('vname').value;
if( vname==null || vname=="")
{
alert("Please input a victim's name");
}
}
function validateVEmail() {
var vemail = document.getElementById('vemail').value;
if( vemail==null || vemail=="")
{
alert("Please input a victim's email");
}
}
<div id="navi">
<nav>
<ul class="fancyNav">
<li id="home">Home</li>
<li id="news">TRUTH</li>
<li id="about">DARE</li>
</ul>
</nav>
</div>
<div id="box">
<form id="truth">
<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" /> <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" /><br><br>
<label> Email:</label> <input type="text" name="vemail" id="vemail" /> <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" onclick="validateFName(); validateLName(); validateGender(); validateDate(); validateVName(); validateVEmail();" /> <br>
</form>
</div>
<input type="submit" onclick="validateFName(); validateLName(); validateGender(); v
typo in function name, onclick="validateFName()...
it should be validateLName()
and you define duplicate
<!DOCTYPE html>
<html> // remove this one
The best possible solution would be to not use any alert boxes at all but instead embed the error message next to the place of the error, but that would be more involved. Instead, to stick with this solution, first add an id to your submit button:
<button type="submit" id="truth-submit">Submit</button>
Then, attach an onclick handler through JavaScript (and rewrite your code to be more re-usable):
// Only run when the window fully loads
window.addEventListener("load", function() {
function validateEmail() {
var email = document.getElementById("email").value;
if (email === null || email === "") {
return "Please input an email address";
}
return "";
}
function validateFName() {
var firstname = document.getElementById("firstname").value;
if (firstname === null || firstname === "") {
return "Please input an first name";
}
return "";
}
function validateLName() {
var lastname = document.getElementById("lastname").value;
if (lastname === null || lastname === "") {
return "Please input an last name";
}
return "";
}
function validateGender() {
var gender = document.getElementById("gender").value;
if (gender === null || gender === "") {
return "Please select a gender";
}
return "";
}
function validateDate() {
var date = document.getElementById("date").value;
if (date === null || date === "") {
return "Please select a date";
}
return "";
}
function validateVName() {
var vname = document.getElementById("vname").value;
if (vname === null || vname === "") {
return "Please input a victim's name";
}
return "";
}
function validateVEmail() {
var vemail = document.getElementById("vemail").value;
if (vemail === null || vemail === "") {
return "Please input a victim's email";
}
return "";
}
document.getElementById("truth-submit").addEventListener("click", function(event) {
// Grab all of the validation messages
var validationMessages = [validateFName(), validateLName(),
validateGender(), validateDate(), validateVName(), validateVEmail()];
var error = false;
// Print out the non-blank ones
validationMessages.forEach(function(message) {
if (message) {
alert(message);
error = true;
}
});
// Stop submission of the form if an error occurred
if (error) {
event.preventDefault();
}
}, false);
}, false);

javascript validation does not work

validateType(), validateStatus(), validateMessage() does not work.
any ideas?
validateEmail() and validateName() works.
I been trying to debug this for a while without any luck. I have exhausted myself.
Thank you for the help!
The form is called contact.
<html>
<head>
<title>Student Contact Form</title>
<link rel="stylesheet" type="text/css" href="homeStyle.css">
<script type="text/javascript">
function focus()
{
name1.focus();
}
function javaScriptValidation()
{
if (validateName() == false)
{
return false;
}
if (validateEmail() == false)
{
return false;
}
if (validateSubject() == false)
{
return false;
}
if (validateType() == false)
{
return false;
}
if (validateStatus() == false)
{
return false;
}
if (validateMessage() == false)
{
return false;
}
return true;
}
function validateName()
{
var letters = /^[A-Za-z]+$/;
if (!letters.test(name1.value))
{
alert("Invalid Name (only letters)");
name1.focus();
return false;
}
}
function validateEmail()
{
var letters = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!letters.test(email.value))
{
alert("Invalid Email");
email.focus();
return false;
}
}
function validateType()
{
var listSelection=document.forms["contact"]["type1"].value;
if(listSelection=="--Please Select--")
{
alert("You must select the reason to contact");
return false;
}
}
function validateStatus()
{
if ((contact.status[0].checked == false ) && (contact.status[1].checked == false ) && (contact.status[2].checked == false ) && (contact.status[4].checked == false))
{
alert("Please select your status");
return false;
}
}
function validateMessage()
{
var letters = /^[A-Za-z]+$/;
if (!letters.test(message.value))
{
alert("please write a message");
message.focus();
return false;
}
}
</script>
</head>
<body onload="focus()">
<div id = "banner">
<img src = "images/logo03.jpg" alt = "Uparty Logo"/>
</div>
<div id = "userAccount">
| HOME <img src = "images/home.png" alt ="event" style = "width:2%"/>
| CREATE EVENT! <img src = "images/event.png" alt ="event" style = "width:2%"/>
| CHANGE PASSWORD <img src = "images/changePassword.jpg" alt = "change password icon" style = "width:2%"/>
| CONTACT US <img src = "images/contact.png" alt ="contact" style = "width:2%"/>
| LOG OUT <img src = "images/Log-Out-icon.png" alt = "logout icon" style = "width:2%"/>
</div>
<div id = "banner">
<img src = "images/Get in Touch.JPG" alt = "contact us"/>
<form name="contact" method="post" action="" onsubmit="return javaScriptValidation()">
<h2>WE'D LOVE TO HEAR FROM YOU</h2>
<p>Your Name [required] <br />
<input type="textbox" name="name" id="name1" class="boxes" size="40"/></p>
Your Email [required]<br />
<input type="textbox" name="email" id="email" class="boxes" size="40"/><br />
<p>Type: <select id="type1" class="type">
<option value="--Please Select--" selected="selected">--Please Select--</option>
<option value="support">Support</option>
<option value="feedback">Feedback</option>
<option value="general">General</option>
</select></p>
<p>College Statues-->
<input type="radio" name="status" value="freshman"/>Freshman
<input type="radio" name="status" value="Sophomore"/>Sophomore
<input type="radio" name="status" value="Junior"/>Junior
<input type="radio" name="status" value="Senior"/>Senior</p>
<p>Subject [required]<br />
<input type="textbox" name="subject" class="boxes" size="40"/><p>
<img src = "images/send a message banner.JPG" alt = "contact picture"/> <br />
Message [required]<br />
<textarea name="message" id="message" rows="15" cols="40"></textarea><br />
<input type="submit" class="submit" value="submit"/>
<input type="reset" class="reset" value="reset"/>
</form>
<img src = "images/background.JPG" alt = "logout icon" style = "width:100%"/>
</div>
</body>
</html>
remove
if (validateSubject() == false)
{
return false;
}
You haven't defined a validateSubject() function
you dont have a function named validateSubject()
which is called here
if (validateSubject() == false)
{
return false;
}
function javaScriptValidation()
{
return validateName() && validateEmail() && validateSubject() && validateType() && validateStatus() && validateMessage();
}
Add ValidateSubject() implementaion and change:
function validateName()
{
var letters = /^[A-Za-z]+$/;
if (!letters.test(name1.value))
{
alert("Invalid Name (only letters)");
name1.focus();
return false;
}
return true; //add this line to each method
}
please replace with the following js
function javaScriptValidation(form) {
var namePattern = /^[A-Za-z]+$/;
var emailPattern = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
// name
if (!namePattern.test(form.name.value)){
alert("Invalid Name (only letters)");
form.name.focus();
return false;
}
//email
if (!emailPattern.test(form.email.value)){
alert("Invalid Email");
form.email.focus();
return false;
}
//type
if(form.type.selectedIndex == 0){
alert("You must select the reason to contact");
form.type.focus();
return false;
}
//status
if((form.status[0].checked == false) && (form.status[1].checked == false) && (form.status[2].checked == false) && (form.status[3].checked == false)){
alert("Please select your status");
return false;
}
//subject
if (!namePattern.test(form.subject.value)){
alert("please write a subject");
form.subject.focus();
return false;
}
//message
if (!namePattern.test(form.message.value)){
alert("please write a message");
form.message.focus();
return false;
}
return true;
}
add name for select box
<select id="type1" class="type" name="type">
add this on form tag onsubmit validation
<form name="contact" method="post" action="" onsubmit="return javaScriptValidation(this)">

Javascript Validation doesn't work

I am new to javascript and I am attempting to create a simple form validation. When I hit the submit button nothing happens. I have been looking at examples for a while and I cannot seem to figure out where I am going wrong. Any suggestions:
HTML:
<form name="myForm" class="appnitro" onsubmit="return validateForm()" action="mysql_connection.php" method="post">
<div class="form_description">
<h2>Patient Record</h2>
<p></p>
</div>
<ul>
<li id="li_1">
<label class="description" for="element_1">&nbspName</label>
<span>
<td width="68%"><input size="15" maxlength="30" class="input" type="text" name="Fname" id="Fname"></td>
<label>First</label>
</span>
<span>
<td width="68%"><input size="15" maxlength="30" class="input" type="text" name="Lname" id="Lname"></td>
<label>Last</label>
</span>
<li class="buttons">
<label class="description" for="element_1">&nbspGender</label>
<span>
<tr>
<select name="Gender">
</tr>
</span>
<option value="Select">Select</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<li class="buttons">
<label class="description" for="element_3">&nbspAge</label>
<span>
<tr>
<select name="Age">
</tr>
</span>
<script type="text/javascript">
listAge()
</script>
</select>
<li class="buttons">
<label class="description" for="element_3">&nbspPhone Number</label>
<span>
<td width="68%"><input size="25" maxlength="50" class="input" type="text" name="Phone" id="Phone"></td>
</span>
<li class="buttons">
<label class="description" for="element_3">&nbspEmail ID</label>
<span>
<td width="68%"><input size="25" maxlength="50" class="input" type="text" name="Email" id="Email"></td>
</span>
<li class="buttons">
<label class="description" for="element_3">&nbspAddress</label>
<span>
<td><textarea cols="25" rows="3" class="input" name="Address" id="Address"></textarea></td>
</span>
<li class="buttons">
<label class="description" for="element_3">&nbspReason For Visit</label>
<span>
<td><textarea cols="25" rows="3" class="input" name="Reason" id="Reason"></textarea></td>
</span>
<li class="buttons">
<label class="description" for="element_3">&nbspAttending Doctor</label>
<span>
<td width="68%"><input size="25" maxlength="50" class="input" type="text" name="Doctor" id="Doctor"></td>
</span>
<li class="buttons">
<input type="submit" value="Submit" />
<input type="reset" value="Reset">
</li>
</ul>
</form>
Javascript:
<script>
function validateForm() {
var Fname = document.forms["myForm"]["Fname"].value;
var Lname = document.forms["myForm"]["Lname"].value;
var Phone = document.forms["myForm"]["Phone"].value;
var Address = document.forms["myForm"]["Address"].value;
var Reason = document.forms["myForm"]["Reason"].value;
var Doctor = document.forms["myForm"]["Doctor"].value;
var email = document.forms["myForm"]["email"].value;
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (Fname == null || Fname == "") {
alert("First name must be filled out");
return false;
}
if (Lname == null || Lname == "") {
alert("Last name must be filled out");
return false;
}
if (Phone == null || Phone == "") {
alert("Phone Number must be filled out");
return false;
}
if (Address == null || Address == "") {
alert("Address must be filled out");
return false;
}
if (Reason == null || Reason == "") {
alert("Reason for Visit must be filled out");
return false;
}
if (Doctor == null || Doctor == "") {
alert("Attending Doctor must be filled out");
return false;
}
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
alert("Not a valid e-mail address");
return false;
}
}
function listAge() {
var i = 1;
for (i = 1; i <= 100; i++) {
document.write("<option value=" + i + ">" + i + "</option>");
}
}
</script>
Your HTML is hideously invalid. Odds are that the browser is trying to perform error recovery and doing things like moving the <form> element outside the table (assuming there is a table, it doesn't show up in your code but you have table data cells in it) so that the submit button is no longer inside it and does not try to submit the form. (This is a known problem with trying to interleave forms a table rows).
Use a validator to find your errors then fix them.
#Quentin is right, you need to clean your HTML code and javascript code.
But you have an error in your Javascript. You need to write a capital E for the Email field. It is case sensitive.
Try with this :
var email = document.forms["myForm"]["Email"].value;
Why not directly use the ID attribute of the element as if you put an ID inside any element it is always preferred to keep it unique. So you can use document.getElementById("ID").value; to get the value of an individual element. Like this :
var firstName = document.getElementById("firstNameTextBox").value;
if(firstName == ''){
message.innerHTML = "First Name is required";
}
I have a demo that you should try.
Demo
Add this JavaScript code and it should word
function validateForm() {
var Fname = document.forms["myForm"]["Fname"].value;
var Lname = document.forms["myForm"]["Lname"].value;
if (Fname == null || Fname == "") {
alert("First name must be filled out");
return false;
}
if (Lname == null || Lname == "") {
alert("Last name must be filled out");
return false;
}
if (Phone == null || Phone == "") {
alert("Phone Number must be filled out");
return false;
}
if (Address == null || Address == "") {
alert("Address must be filled out");
return false;
}
if (Reason == null || Reason == "") {
alert("Reason for Visit must be filled out");
return false;
}
if (Doctor == null || Doctor == "") {
alert("Attending Doctor must be filled out");
return false;
}
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
alert("Not a valid e-mail address");
return false;
}
}
function listAge() {
var i = 1;
for (i = 1; i <= 100; i++) {
document.write("<option value=" + i + ">" + i + "</option>");
}
}
I believe the problem is that you try to take some values from fields that not exists at least from the code that you provided! Just copy the code above and it should work for sure!

Categories

Resources