Form Validation in JavaScript (without using jquery) - javascript

I have this assignment in my class where we are to make a simple form with three required fields (out of five). I am having problems with getting my code to work.
This is via my professor...with what he wants
{
On submitting the form, the browser should check that :
Values for the required fields have been entered
Use regular expressions to check that the form of the entered input is proper for the email, telephone, and website fields. The forms to check for are:
Email: [alphanumeric string including . and _ ]# [alphanumeric string including . and _ ]. [alpha string]
Telephone: Either (ddd)ddd-dddd or ddd-ddd-dddd etc
Website: www.[alphanumeric string including . _ -].[com or net etc]
If any error is found, the form should not be submitted and appropriate error messages should be generated.
}
All validation must be "client side" i.e. on the browser using Javascript (not on any server and no Jquery or any programming other than Javascript and the required HTML). Use of any authoring tools is strictly and expressly forbidden.
This what I have now. Please help. Below is the code. What am I doing wrong?
<script language = "JavaScript">
<!--
function validateForm(){
//This is to check that required fields are filled
var x = document.contact.Name.value;
var y = document.contact.Email.value;
var z = document.contact.Website.value;
var p = document.contact.Phone.value;
if(x==null || x ==""){
alert('Name must be filled out');
return false;
}
if (y ==null || y == ""){
alert('Email must be filled out');
return false;
}
if (z == null || z == ""){
alert('Website must be filled out');
return false;
}
if(!isEmail()){
alert('This is not a correct Email format');
}
if (!isTelephone()){
var errorText = document.createTextNode(
"This is not a correct Phone number format");
}
if(!isWeb()){
errorText = document.createTextNode(
"This is not the correct Website format");
}
}
function isTelephone(){
//This checks that the phone number is in the required format
return document.contact.Phone.value.match(
/^\(\d\d\d-d\d\d\-\d\d\d\d$/);
}
function isEmail(){
//This is for checking email format
return document.contact.Email.value.match(
/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/);
}
function isWeb(){
return document.contact.Website.value.match(
/^([wW]{3}\.)?[a-zA-Z0-9\-.]{3,}\[a-zA-Z]{2,}(\.[a‌​-zA-Z]{2,})?$/);
}
-->
</script>
<body>
<form name="contact" action="" method="post" onSubmit = "return validateForm();">
Name: <input type="textbox" name="Name" value="" > <font color = red>*Required </font><br>
Company: <input type="textbox" name="Company" value="" > <font color = red>Optional </font><br>
Email: <input type="textbox" name="Email" value="" > <font color = red>*Required </font><br>
Telephone: <input type="textbox" name="Telephone" value="" > <font color = red>Optional </font><br>
Website: <input type="textbox" name="Website" value="" ><font color = red>*Required </font><br>
<input type="submit" value="Submit Contact Details">
<input type="reset" value="Clear"
ONCLICK="
alert('This will clear the form.');
Name.value=' '
Company.value=' '
Email.value=' '
Telephone.value=' '
Website.value=' '"><br>
</form>
</body>
</html>

Try this out:- https://jsfiddle.net/vduwxjmv/
This can be done without JavaScript also using required attribute at each html control for which value is mandatory. And for clear you can use input type as reset.
HTML:-
<form name="contact" action="" method="post">
Name: <input type="textbox" name="Name" value="" required> <font color = red>*Required </font><br>
Company: <input type="textbox" name="Company" value=""> <font color = red>Optional </font><br>
Email: <input type="textbox" name="Email" value="" required> <font color = red>*Required </font><br>
Telephone: <input type="textbox" name="Telephone" value="" > <font color = red>Optional </font><br>
Website: <input type="textbox" name="Website" value="" required><font color = red>*Required </font><br>
<input type="submit" value="Submit Contact Details">
<input type="reset" value="Clear" />

You can do a check by using the following JavaScript code
var result = $("#form")[0].checkValidity();
or you may change input button
<input type="submit" value="Submit Contact Details">

<!DOCTYPE html>
<html>
<body>
<form name="contact" method="post">
Name: <input type="text" class="form-control" name="Name" placeholder="Name" required="required" /> <font color = red>*Required </font><br>
Company: <input type="text" class="form-control" name="Company" placeholder="Company" /> <font color = red>Optional </font><br>
Email: <input type="email" class="form-control" name="Email" placeholder="Email" required="required" /> <font color = red>*Required </font><br>
Telephone: <input type="text" class="form-control" name="Telephone" placeholder="Telephone"/> <font color = red>Optional </font><br>
Website: <input type="text" class="form-control" name="Website" placeholder="Website" required="required" /><font color = red>*Required </font><br>
<input type="submit" value="Submit Contact Details">
<input type="reset" value="Clear"><br>
</form>
</body>
</html>
change the type from button to submit.
on giving the type as reset ,it will clear the contents.
on giving required="required", that field will be considered as a mandatory one.

<html>
<head>
<script language = "JavaScript">
function validateForm(thisVar){ alert('method Called From: ');alert(thisVar.value);alert(thisVar.name);
//This is to check that required fields are filled
var x = document.contact.Name.value;
var y = document.contact.Email.value;
var z = document.contact.Website.value;
var p = document.contact.Phone.value;
if(x==null || x ==""){
alert('Name must be filled out');
return false;
}
if (y ==null || y == ""){
alert('Email must be filled out');
return false;
}
if (z == null || z == ""){
alert('Website must be filled out');
return false;
}
if(!isEmail()){
alert('This is not a correct Email format');
}
if (!isTelephone()){
var errorText = document.createTextNode(
"This is not a correct Phone number format");
}
if(!isWeb()){
errorText = document.createTextNode(
"This is not the correct Website format");
}
}
function isTelephone(){
//This checks that the phone number is in the required format
return document.contact.Phone.value.match(
/^\(\d\d\d-d\d\d\-\d\d\d\d$/);
}
function isEmail(){
//This is for checking email format
return document.contact.Email.value.match(
/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/);
}
function isWeb(){
return document.contact.Website.value.match(
/^([wW]{3}\.)?[a-zA-Z0-9\-.]{3,}\[a-zA-Z]{2,}(\.[a‌​-zA-Z]{2,})?$/);
}
</script>
</head>
<body>
<form name="contactForm" action="" method="post" onSubmit = "return validateForm(this);">
Name: <input type="textbox" name="Name" value="" > <font color = red>*Required </font><br>
Company: <input type="textbox" name="Company" value="" > <font color = red>Optional </font><br>
Email: <input type="textbox" name="Email" value="" > <font color = red>*Required </font><br>
Telephone: <input type="textbox" name="Telephone" value="" > <font color = red>Optional </font><br>
Website: <input type="textbox" name="Website" value="" ><font color = red>*Required </font><br>
<input type="submit" value="Submit Contact Details" onclick="validateForm(this);">
<input type="reset" value="Clear"
ONCLICK="
alert('This will clear the form.');
Name.value=' '
Company.value=' '
Email.value=' '
Telephone.value=' '
Website.value=' '"><br>
</form>
</body>
</html>
You can validate it by two ways ---
use Submit type button
call validationForm on button click
Like --
<input type="submit" value="Submit Contact Details">
or
<input type="button" onclick="return validationForm();" value="Submit Contact Details">
you can check method call from to times 1st from onclick 2nd from onsubmit
Dont forget to appreciate (vote up).

Related

How to check whether an email address contains an # sign and a '.'. in html and javascript

I'm performing some validation checks on some inputs from the user. I was wondering how do I check that the email entered by the user contains an # symbol and a '.' as well as characters before and after the # symbol. Thanks in advance for answering.
<!DOCTYPE html>
<html>
<head>
<script language="JavaScript">
function showInput() {
var comment = document.getElementById("com").value;
var first = document.getElementById("fname").value;
var last = document.getElementById("lname").value;
var dateOfVisit = document.getElementById("date").value;
var firstError = document.getElementById('firstNameError');
var lastError = document.getElementById('lastNameError');
var displayEl = document.getElementById('displayname');
if (!first) {
firstError.setAttribute('style', 'display: block; color: red');
} else {
firstError.setAttribute('style', 'display: none;');
}
if (!last) {
lastError.setAttribute('style', 'display: block; color: red');
} else {
lastError.setAttribute('style', 'display: none;');
}
displayEl.innerHTML =
first + " " + last + " visited this on " + dateOfVisit + " and said '" + comment || 'not a thing...' + "'";
}
</script>
<title>Great Pyramid of Giza</title>
</head>
<body>
<h2>Leave A Review!</h2>
<p>Have you been to this wonder of the world? If so, leave a review.</p>
<form>
First Name:<br>
<input type = "text" name="firstname" id="fname"><br>
<span style="display: none;" id="firstNameError">First name is required!</span>
Last Name:<br>
<input type = "text" name="lastname" id="lname"><br>
<span style="display: none;" id="lastNameError">Last name is required!</span>
Email Address:<br>
<input type = "text" name="email"><br>
Date of Visit:<br>
<input type = "text" name="date" id="date"><br>
Comment:<br>
<input type = "text" name="comment" size="70" id="com"><br>
</form>
<input type = "submit" value="Submit" onclick="showInput();">
<h2>Comments:</h2>
<p><span id='displayname'></span></p>
</body>
</html>
You can create a email input and validate against that instead of using any regex...
function isEmail(email) {
var input = document.createElement('input')
input.type = 'email'
input.value = email
return input.validity.valid
}
console.log(isEmail('admin#example.com'))
console.log(isEmail('#example.com'))
But why bother??? just use <input type="email"> and skip all javascript nonsens
<form>
<input type="text" name="firstname" required autocomplete="given-name">
<input type="text" name="lastname" required autocomplete="family-name">
<input type="email" name="email" autocomplete="email">
<input type="date" min="2018-04-21" name="date">
<textarea name="comment"></textarea>
<input type="submit">
</form>
ps, use form.onsubmit instead of btn.onclick (way better)
read more about constraint validation and inputs

How to make a submit button work on a questionnaire

I am making a health questionnaire, I am having a few problems with it. The main problem is the else section. Can someone tell me why it isn't working and help me sort it?
The code I have is:
Assignment 4
Health Questionnaire
<body>
<form name="form1">
Please enter the following details: <p>
First Name: <br>
<input type="text" name="txtFirstName"> size="20" maxlength="20"> <p>
Surname: <br>
<input type="text" name="txtSurName"> size="30" maxlength="20"> <p>
Age: <br>
<input type="text" name="txtAge" size="3" maxlength="3"> <p>
Address Line 1: <br>
<input type="text" name="txtAddressline1" size="30" maxlength="30"> <p>
Address Line 2: <br>
<input type="text" name="txtAddressline2" size="30" maxlength="30"> <p>
City: <br>
<input type="text" name="txtCity" size="20" maxlength="20"> <p>
County: <br>
<input type="text" name="txtCounty" size="20" maxlength="20"> <p>
Post Code: <br>
<input type="text" name="txtPostCode" size="10" maxlength="10"> <p>
<input type="submit" value="Check Details" name=validateForm
onclick="validateForm_onclick()">
<script type ="text/javascript">
function validateForm_onclick()
{
var myForm = document.form1;
if(myForm.txtAge.value === "" || myForm.txtFirstName.value === ""||
myForm.txtSurName.value === ""|| myForm.txtAddressline1.value === ""||
myForm.txtAddressline2.value === ""|| myForm.txtCity.value === ""||
myForm.txtCounty.value === ""|| myForm.txtPostCode.value === "")
{
alert("Please complete all of the form");
if(myForm.txtFirstName.value ==="")
{
myForm.txtFirstName.focus();
}
else
{
myForm.txtSurName.focus();
}
else
{
myForm.txtFirstName.focus();
}
else
{
myForm.txtAge.focus();
}
else
{
myForm.txtAddressline1.focus();
}
else
{
myForm.txtAddressline2.focus();
}
else
{
myForm.txtCity.focus();
}
else
{
myForm.txtCounty.focus();
}
else
{
myForm.txtPostCode.focus();
}
}
else
{
alert("Thanks for completing the form " + myForm.txtName.value);
myForm.submit();
}
}
</script
</form>
</body>
I need to also keep the sizes on the names but need to hide that from the user.
Can someone give me some advice on how to change this?
Your form does not have a submit button.
Your code:
<input type="button" value="Check Details" name=validateForm
onclick="validateForm_onclick()">
Rectified code:
<input type="submit" value="Check Details" name=validateForm
onclick="validateForm_onclick()">
Also, the long list of else is illegal in JavaScript.
form name=form1 needs to have quotes: form name="form1"
And in case you don't want to use submit but stick to a button, insert this in your javascript:
else
{
alert("Thanks for completing the form " + myForm.txtName.value);
myForm.submit();
}

javascript validation - Javascript not running

I'm trying to validate the inputs, so far I've created only two rules. One to test the phone number and another to test if the passwords entered at the same.
My problem is that for some reason my javascript isn't validating input. I have it referenced in <script>, I call it in the form onsubmit="return validate()". For some reason even with using an alert test to check that its run, that fails. So, I'm not really sure what's wrong, I could do with some extra eyes.
function validate() {
var errMsg = ""; /* stores the error message */
var result = true; /* assumes no errors */
var phonetest1 = true;
var phonetest2 = true;
/*get values from the form*/
var FirstName = document.getElementById("FirstName").value;
var Lastname = document.getElementById("Lastname").value;
var Email = document.getElementById("Email").value;
var Password = document.getElementById("Password").value;
var ConPassword = document.getElementById("ConPassword").value;
var Phone = document.getElementById("Phone").value;
var phonepatt1 = (/\(|0|\d|\)|\d|\d|\d|\d|\d|\d|\d|\d/);
var phonepatt2 = (/0|\d|\s|\d|\d|\d|\d|\d|\d|\d|\d/);
/* Rule one */
if (!phonepatt1.test(Phoneno)) {
phonetest1 = false;
}
if (!phonepatt2.test(Phoneno)) {
phonetest2 = false;
}
if (phonetest1 == false && phonetest2 == false) {
errMsg += "Your Phone number is incorrect .\n";
result = false;
}
alert("I'm running"); /* This isn't working */
/* Rule two */
if (ConPassword != Password) {
errMsg += "Please confirm your password .\n";
result = false;
}
if (errMsg != "") { //only display message box if there is something to show
alert(errMsg);
}
return result;
}
<H1>store Home Page</H1>
<p>Customer Registration: Register
<p>Customer Login: Login
<p>Manager Login Administrators
<form id="UserDetails" method="post" onsubmit="return validate()" action="index.htm">
<fieldset id="Details">
<legend>Your details:</legend>
<p>
<label for="FirstName">First Name</label>
<input type="text" name="FirstName" id="FirstName" pattern="[a-zA-Z]+" size="20" maxlength="20" required="required" />
</p>
<p>
<label for="Lastname">Last Name</label>
<input type="text" name="LastName" id="Lastname" pattern="[a-zA-Z]+" size="20" maxlength="20" required="required" />
</p>
<p>
<label for="Email">Email</label>
<input type="text" name="Email" id="Email" size="20" maxlength="20" required="required" />
</p>
<p>
<label for="Password">Password</label>
<input type="text" name="Password" id="Password" size="20" maxlength="20" required="required" />
</p>
<p>
<label for="ConPassword">Confirm Password</label>
<input type="text" name="ConPassword" id="ConPassword" size="20" maxlength="20" required="required" />
</p>
<p>
<label for="Phone">Phone Number</label>
<input type="text" name="Phone" id="Phone" maxlength="12" size="12" placeholder="(03)92251515" />
</p>
<input type="submit" value="Register Now!" />
<input type="reset" value="Reset" />
</fieldset>
</form>
You have wrog name in your JavaScript (should be Phone instead of Phoneno):
if (!phonepatt1.test(Phone)) {
phonetest1 = false;
}
if (!phonepatt2.test(Phone)) {
phonetest2 = false;
}

HTML Validation JS without using PHP

I made an application for people to fill out an application. I did some of the in form validation but now I want to ensure that when the user hits the submit button it checks to ensure that all field are filled out. I am stuck and cannot figure out the last part of this puzzle.
I believe all I need to make this work is a Application.js If someone could take a look at this and let me know what if anything I am missing. I did not include the CSS sheet or photos. Thank you for taking the time to help.
Here is the form. "Application.html"
<!DOCTYPE html>
<html>
<head>
<center><h1>AIFC Application Form</h1></center>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<title>AIFC Application</title>
<meta charset="utf-8">
<meta name="author" content="Paul Skinner">
<link rel="stylesheet" type="text/css" href="Application.css" />
<style type="text/css">
</style>
<script src="Application.js"></script>
<script src="Application_Library.js"></script>
<script type="text/javascript">
function updateTotal() {
var basePrice = 50;
var optionsPrice = 0;
var memberPrice = 0;
function checkPayment() {
if (document.getElementById('payment0').checked) {
optionsPrice += 1;
}
if (document.getElementById('payment1').checked) {
optionsPrice += 9.6;
}
} // end of checking for payment
function checkJumper() {
if (document.getElementById('jumper0').checked) {
optionsPrice += 0;
}
if (document.getElementById('jumper1').checked) {
optionsPrice += 4.4;
}
} // end of checking for Jumper
function checkMembership() {
if (document.getElementById('membership').value == 'Basic') {
memberPrice += 75;
}
if (document.getElementById('membership').value == 'Silver') {
memberPrice += 125;
}
if (document.getElementById('membership').value == 'Gold') {
memberPrice += 150;
}
} // end of check membership function
checkPayment();
checkJumper();
checkMembership();
var totalPrice = basePrice + (optionsPrice * memberPrice);
document.getElementById('optionsPrice').innerHTML = optionsPrice;
document.getElementById('memberPrice').innerHTML = "$ " + memberPrice;
document.getElementById('totalPrice').innerHTML = "$ " + totalPrice;
}
</script>
</head>
<body>
<div id="top">
<nav class="horizontalNav">
<ul>
<li>Home</li>
<li>Application</li>
<li>Who We Are</li>
<li>Our Packages</li>
</ul>
</nav></div>
<section>
<table>
<tr style="white-space:nowrap; clear:both">
<td><img src="Images/girl punching.jpg" alt="Girl Punching" style=" float:left; height:200px" /></td>
<td><img src="images/fitness.jpg" alt="Weights" style=" float:right; height:200px; width:900px" /></td>
</tr>
</table>
</section>
<form action="#" method="get" name="application" id="application" >
<div id="form">
<fieldset>
<legend>Payment Type</legend><br>
<input type="radio" name="payment" id="payment0" value="payment0" onchange="updateTotal()"> Monthly membership <br>
<input type="radio" name="payment" id="payment1" value="payment1" onchange="updateTotal()"> Yearly membership <b>Big Savings!</b> <br><br>
</fieldset>
<fieldset>
<legend>Choose a Location</legend><br>
<input type="radio" name="jumper" id="jumper0" value="jumper0" onchange="updateTotal()"> Single Gym location
<input type="radio" name="jumper" id="jumper1" value="jumper1" onchange="updateTotal()"> All Locations <br><br>
</fieldset>
<fieldset>
<legend>Membership Type</legend><br>
<select name="membership" id="membership" onchange="updateTotal()">
<option value="Basic">Basic Membership ($75)</option>
<option value="Silver">Silver Membership ($125)</option>
<option value="Gold">Gold Membership ($150)</option><br>
</select>
</fieldset>
<fieldset>
<legend>Sex</legend><br>
<input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female<br>
</fieldset>
</div>
<div id="prices">
<table>
<tr><td>Membership Application Fee</td><td id="basePrice">$50</td></tr>
<tr><td>Option factor</td><td id="optionsPrice"></td></tr>
<tr><td>Membership</td><td id="memberPrice"></td></tr>
<tr><td>Total</td><td id="totalPrice"></td></tr>
</table>
</div>
<div id="info">
<fieldset>
<legend>Personal Information</legend>
<label for="first_name">First Name:</label>
<input type="text" id="firstname" name="first" required autofocus title="First Name" placeholder="First Name" />
<span id="first_name_error"> </span><br>
<label for="last_name">Last Name:</label>
<input type="text" id="lastname" name="last" required title="Last Name" placeholder="Last Name"/>
<span id="last_name_error"> </span><br>
<label for="address">Address:</label>
<input type="text" id="address" name="address" required title="Address" placeholder="Address"/>
<span id="address_error"> </span><br>
<label for="city">City:</label>
<input type="text" id="city" name="city" required title="City" placeholder="City"/>
<span id="city_error"> </span><br>
<label for="state">State:</label>
<input type="text" id="state" maxlength="2" name="State" required title="State" placeholder="State"/>
<span id="state_error"> </span><br>
<label for="zip_code">Zip Code:</label>
<input type="text" id="zip" name="zip" required title="Zip Code" placeholder="Zip Code" pattern="\d{5}([\-]\d{4})?"/>
<span id="zip_error"> </span><br>
<label for="phone_number">Phone Number:</label>
<input type="text" id="phone" name="phone" required title="Optional Phone Number 999-999-9999" placeholder="999-999-9999" pattern="\d{3}[\-]\d{3}[\-]\d{4}"/>
<span id="phone_error"> </span><br>
<label for="date_of_birth">Date of Birth:</label>
<input type="date" name="date" required title="MM-DD-YYYY"/>
<span id="date_error"> </span><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required title="Email" placeholder="Email Address"/>
<span id="email_error"> </span>
<br>
</fieldset>
<br><br><center><input type="submit" id="submit" value="Become a Member"></center>
<br><center><input type="Reset" id="btn1" value="Reset Form"></center>
</div>
<br><br><div class="footer">
<address><center>
<b>American InterContinental Fitness Center</b> ☀
1578 Perseverance Lane ☀
Simple City, IL 60001
<br/> (630)432-1425
</address></center>
<br>
</div>
</form>
</body>
</html>
The next is the js: "Application_Library.js"
var $ = function (id) { return document.getElementById(id); }
var application = function () {
// All the different fields
this.field = [];
this.field["first_name"] = {};
this.field["last_name"] = {};
this.field["address"] = {};
this.field["city"] = {};
this.field["state"] = {};
this.field["zip"] = {};
this.field["phone"] = {};
this.field["date"] = {};
this.field["email"] = {};
// Field messages
this.field["state"].message = "Please use only a two letter State abbreviation.";
this.field["zip"].message = "Please use a 5 or 9 digit Zip Code";
this.field["phone"].message = "Please use 123-456-7890 format.";
this.field["email"].message = "Must be a vaild email address.";
// Error messages
this.field["email"].required = "Email is required";
this.field["confirmemail"].required = "Please confirm your email!";
this.field["confirmemail"].noMatch = "Emails do not Match!", "email";
this.field["first_name"].required = "First names are required.";
this.field["last_name"].required = "Last names are required.";
this.field["address"].required = "An Address is required";
this.field["city"].required = "A City is required";
this.field["state"].required = "A State is required";
this.field["state"].isState = "State invalid";
this.field["zip"].required = "A Zip code is required.";
this.field["zip"].isZip = "Zip code is invalid";
this.field["phone"].required = "A phone number is required";
this.field["phone"].isPhone = "The phone number is invalid";
this.field["date"].required = "Your date of birth is required";
}
Instead of writing your own javascript validation you can use the jQuery "form Validation Plug-in", which is an excellent tool for web pages to validate data entries at the client side using JavaScript. It's very simple to use.
Here is a sample tutorial
http://www.codeproject.com/Articles/213138/An-Example-to-Use-jQuery-Validation-Plugin
You should implement server side validation also for best security.
You can't just check data on JavaScript, you should also check it on server-side, because the client side is more accessible and user can change the JavaScript or even disable it, so the data would be invalidated.
You should write server-side validation too.
You forgot to show the Application.js file.
Also you can use HTML5 validation, without using any JavaScript:
http://www.sitepoint.com/html5-form-validation/

Why isn't my instantaneous validation displaying anything?

I have a form that has a number of fields on it. When the user inputs anything, the field should automatically begin sending feedback as to whether or not the input is valid. The javascript code listed is suppose to handle the instantaneous feedback but it gives no reply whatsoever. It is also suppose to stop the form from being submitted if any of the user's input does not match the regular expressions. The regular expressions don't work either but they were working perfectly fine before I used the innerHTML. I would go back to using alerts if using innerHTML wasn't mandatory.
function insert() {
var valid = true;
document.getElementById("MessNM").innerHTML = "";
if (!document.getElementById("name").value.match(/^^[A-Z]{1}[a-z]{3,7}$/)) {
document.getElementById("MessNM").innerHTML = " Please input a proper name.";
valid = false;
}
document.getElementById("MessPS").innerHTML = "";
if (!document.getElementById("password").value.match(/^[a-zA-Z0-9]{4,8}$/)) {
document.getElementById("MessPS").innerHTML = " Please input a proper password with numbers and letters.";
valid = false;
}
document.getElementById("MessPSC").innerHTML = "";
if (document.getElementById("passwordcheck").value != document.getElementById("password").value) {
document.getElementById("MessPSC").innerHTML = " Password does not match.";
valid = false;
}
document.getElementById("MessAD").innerHTML = "";
if (!document.getElementById("address").value.match(/^[a-zA-Z0-9\s,'-]{5,40}$/)) {
document.getElementById("MessAD").innerHTML = " Address is not valid";
valid = false;
}
document.getElementById("MessZC").innerHTML = "";
if (!document.getElementById("zipcode").value.match(/^[0-9]{5}$/)) {
document.getElementById("MessZC").innerHTML = " Please input a proper Zipcode.";
valid = false;
}
if (!document.getElementById("zipcode").value.match(/^[0-9]{5}(-[0-9]{4})?$/)) {
document.getElementById("MessZC").innerHTML = " Please input a proper Zipcode.";
valid = false;
} else {
return valid;
}
}
function test() {
var result = true;
if (!insert()) {
result = false;
}
return result;
}
This is the html form that the javascript function is referencing.
<form name="Insert" id="I2" action="order.php" method="post" style="display: none;" onsubmit="return test()">
<p align="left">
<div id="texter">
<input type=text id="name" required="required" onkeyup="insert()" name="name" autocomplete="off" autofocus>Name <span id="MessNM"></span>
<br>
<input type=email id="email" required="required" onkeyup="insert()" name="email">Email Address <span id="MessEM"></span>
<br>
<input type=password id="password" required="required" onkeyup="insert()" name="password">Password <span id="MessPS"></span>
<br>
<input type=password id="passwordcheck" required="required" onkeyup="insert()" name="passwordcheck">Confirm Password <span id="MessPSC"></span>
<br>
<input type=text id="address" required="required" onkeyup="insert()" name="address">Address <span id="MessAD"></span>
<br>
<input type=text id="zipcode" required="required" onkeyup="insert()" name="zipcode">Zipcode <span id="MessZC"></span>
<br>
</div>
<input type="submit" value="submit" onclick="test()">
<input type="reset" value="Clear All">
<br>
<br>
</form>
There are several issues I see.
You have style="display: none;" on the form which makes the whole form invisible.
Your validation function returns false on the first failed validation which means you're only going to show an error message for the first invalid field, e.g. if e-mail address and zip code are invalid you'll only get a message for e-mail address.
The regular expression for the address validation is broken.
When the password confirmation error is fixed the error message doesn't clear.
By the fact that you say it was working when you used alerts, I'm guessing the main issue you're talking about is caused by the fact that each field validation returns false. You probably just had alerts before and returned a boolean at the end of the function. Here's a solution that addresses that issue and the others I mentioned above.
<form name="Insert" id="I2" action="order.php" method="post" onsubmit="return test()">
<p align="left">
<div id="texter">
<input type=text id="name" required="required" onkeyup="insert()" name="name" autocomplete="off"/>Name <span id="MessNM"></span>
<br>
<input type="email" id="email" required="required" onkeyup="insert()" name="email">Email Address <span id="MessEM"></span>
<br>
<input type="password" id="password" required="required" onkeyup="insert()" name="password">Password <span id="MessPS"></span>
<br>
<input type="password" id="passwordcheck" required="required" onkeyup="insert()" name="passwordcheck">Confirm Password <span id="MessPSC"></span>
<br>
<input type="text" id="address" required="required" onkeyup="insert()" name="address">Address <span id="MessAD"></span>
<br>
<input type="text" id="zipcode" required="required" onkeyup="insert()" name="zipcode">Zipcode <span id="MessZC"></span>
<br>
</div>
<input type="submit" value="submit" onclick="test()">
<input type="reset" value="Clear All">
<br>
<br>
</form>
function insert() {
var valid = true;
document.getElementById("MessNM").innerHTML = "";
if (!document.getElementById("name").value.match(/^^[A-Z]{1}[a-z]{3,7}$/)) {
document.getElementById("MessNM").innerHTML = " Please input a proper name.";
valid = false;
}
document.getElementById("MessPS").innerHTML = "";
if (!document.getElementById("password").value.match(/^[a-zA-Z0-9]{4,8}$/)) {
document.getElementById("MessPS").innerHTML = " Please input a proper password with numbers and letters.";
valid = false;
}
document.getElementById("MessPSC").innerHTML = "";
if (document.getElementById("passwordcheck").value != document.getElementById("password").value) {
document.getElementById("MessPSC").innerHTML = " Password does not match.";
valid = false;
}
document.getElementById("MessAD").innerHTML = "";
if (!document.getElementById("address").value.match(/^[a-zA-Z0-9\s,'-]*$/)) {
document.getElementById("MessAD").innerHTML = " Address is not valid";
valid = false;
}
document.getElementById("MessZC").innerHTML = "";
if (!document.getElementById("zipcode").value.match(/^[0-9]{5}$/)) {
document.getElementById("MessZC").innerHTML = " Please input a proper Zipcode.";
valid = false;
}
if (!document.getElementById("zipcode").value.match(/^[0-9]{5}(-[0-9]{4})?$/)) {
document.getElementById("MessZC").innerHTML = " Please input a proper Zipcode.";
valid = false;
}
return valid;
}

Categories

Resources