A Simple Form with Validation in JavaScript [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I would like to modify a JavaScript Code and add an extra field such as:
The first text box for the user to enter his/her address,
The second text box for the user to enter a telephone number.
The Code looks like so:
var myForm = document.form1;
function btnCheckFormClick(e) {
var txtName = myForm.txtName;
var txtAge = myForm.txtAge;
if (txtAge.value == "" || txtName.value == "") {
alert("Please complete all of the form");
if (txtName.value == "") {
txtName.focus();
} else {
txtAge.focus();
}
} else {
alert("Thanks for completing the form " + txtName.value);
}
}
function txtAgeBlur(e) {
var target = e.target;
if (isNaN(target.value)) {
alert("Please enter a valid age");
target.focus();
target.select();
}
}
function txtNameChange(e) {
alert("Hi " + e.target.value);
}
myForm.txtName.addEventListener("change", txtNameChange);
myForm.txtAge.addEventListener("blur", txtAgeBlur);
myForm.btnCheckForm.addEventListener("click", btnCheckFormClick);
<form action="" name="form1">
Please enter the following details:
<p>
Name:
<input type="text" name="txtName" />
</p>
<p>
Age:
<input type="text" name="txtAge" size="3" maxlength="3" />
</p>
<p>
<input type="button" value="Check details" name="btnCheckForm">
</p>
</form>
Here is what I tried already BUt it's not working(Not Validation):
var myForm = document.form1;
function btnCheckFormClick(e) {
var txtName = myForm.txtName;
var txtAge = myForm.txtAge;
var txtAddress = myForm.txtAddress;
var txtTelNumber = myForm.txtTelNumber;
if (txtAge.value == "" || txtName.value == "" && txtAddress.value == "" || txtTelNumber.value == "") {
alert("Please complete all of the form");
if (txtName.value == "" && txtAddress.value == "" && txtTelNumber.value == "") {
txtName.focus();
} else {
txtAge.focus();
} else {
txtAddress.focus();
} else {
txtTelNumber.focus();
} else {
alert("Thanks for completing the form " + txtName.value);
}
}
}
function txtAgeBlur(e) {
var target = e.target;
if (isNaN(target.value)) {
alert("Please enter a valid age");
target.focus();
target.select();
}
}
function txtTelNumberBlur(e) {
var target = e.target;
if (isNaN(target.value)) {
alert("Please enter a valid number");
target.focus();
target.select();
}
}
function txtAddressChange(e) {
alert("Your address is: " + e.target.value);
}
function txtNameChange(e) {
alert("Hi " + e.target.value);
}
myForm.txtName.addEventListener("change", txtNameChange);
myForm.txtAge.addEventListener(, txtAgeBlur);
myForm.txtAddress.addEventListener("change", txtAddressChange);
myForm.txtTelNumber.addEventListener("change", txtTelNumberBlur);
myForm.btnCheckForm.addEventListener("click", btnCheckFormClick);
<form action="" name="form1">
Please enter the following details:
<p>
Name:
<input type="text" name="txtName" />
</p>
<p>
Age:
<input type="text" name="txtAge" size="3" maxlength="3" />
</p>
Address:
<input type="text" name="txtAddress" size="40" maxlength="25" />
</p>
Telephone Number:
<input type="text" name="txtTelNumber" size="20" maxlength="10" />
</p>
<p>
<input type="button" value="Check details" name="btnCheckForm">
</p>
</form>
Can anyone tell me what am I doing wrong and point me out to where look at?
Thanks.

You can't have multiple else blocks for the same if. You should be checking each field in a separate else if block.
And in the outer if, all the checks must be connected with ||. You had a mix of && and ||.
var myForm = document.form1;
function btnCheckFormClick(e) {
var txtName = myForm.txtName;
var txtAge = myForm.txtAge;
var txtAddress = myForm.txtAddress;
var txtTelNumber = myForm.txtTelNumber;
if (txtAge.value == "" || txtName.value == "" || txtAddress.value == "" || txtTelNumber.value == "") {
alert("Please complete all of the form");
if (txtName.value == "") {
txtName.focus();
} else if (txtAge.value == "") {
txtAge.focus();
} else if (txtAddress.value == "") {
txtAddress.focus();
} else if (txtTelNumber.value == "") {
txtTelNumber.focus();
}
} else {
alert("Thanks for completing the form " + txtName.value);
}
}
function txtAgeBlur(e) {
var target = e.target;
if (isNaN(target.value)) {
alert("Please enter a valid age");
target.focus();
target.select();
}
}
function txtTelNumberBlur(e) {
var target = e.target;
if (isNaN(target.value)) {
alert("Please enter a valid number");
target.focus();
target.select();
}
}
function txtAddressChange(e) {
alert("Your address is: " + e.target.value);
}
function txtNameChange(e) {
alert("Hi " + e.target.value);
}
myForm.txtName.addEventListener("change", txtNameChange);
myForm.txtAge.addEventListener("blur", txtAgeBlur);
myForm.txtAddress.addEventListener("change", txtAddressChange);
myForm.txtTelNumber.addEventListener("change", txtTelNumberBlur);
myForm.btnCheckForm.addEventListener("click", btnCheckFormClick);
<form action="" name="form1">
Please enter the following details:
<p>
Name:
<input type="text" name="txtName" />
</p>
<p>
Age:
<input type="text" name="txtAge" size="3" maxlength="3" />
</p>
Address:
<input type="text" name="txtAddress" size="40" maxlength="25" />
</p>
Telephone Number:
<input type="text" name="txtTelNumber" size="20" maxlength="10" />
</p>
<p>
<input type="button" value="Check details" name="btnCheckForm">
</p>
</form>

Related

Javascript form validation. No error message. No popup

I need some help getting JS form validation working.
I have form rules in a .js script file I've linked to in the html head.
Example of for rule:
function IsValid4DigitZip( str ) {
// Return immediately if an invalid value was passed in
if (str+"" == "undefined" || str+"" == "null" || str+"" == "")
return false;
var isValid = true;
str += "";
// Rules: zipstr must be 5 characters long, and can only contain numbers from
// 0 through 9
if (IsBlank(str) || (str.length != 4) || !IsInt(str, false))
isValid = false;
return isValid;
} // end IsValid4DigitZip
This is my html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>orderbooks</title>
<link rel="stylesheet" href="styles.css">
<script src="datavalidation.js"></script>
<script type="text/javaScript">
function validate(orderbooks){
var digits="0123456789"
var temp
if ( IsValid4DigitZip(document.orderbooks.Postcode.value) ) {
// Zip code is valid
} else {
alert("Invalid postcode:)
// Zip code is invalid
}
return true
}
</script>
</head>
<body>
<form name="orderbooks" onSubmit="return validate(orderbooks)" >
Name: <input type="text" size="20" name="Name">
Street Number: <input type="text" size="5" name="streetnumber" maxlength="5">
Street Name: <input type="text" size="20" name="streetname" maxlength="25">
Postcode: <input type="text" size="4" name="postcode" maxlength="4">
Telephone: <input type="text" size="11" name="telephone" maxlength="11">
Email: <input type="text" size="20" name="email" maxlength="50">
<input type="reset" value="Clear the Form">
<input type="submit" value="Submit Form">
</form>
</body>
</html>
What am I doing wrong? I can't get it to show the alert or warning.
OK I got the postcode to work with a error message! I have another question.
If I wanted to add this form validation rule:
function IsNum( numstr ) {
// Return immediately if an invalid value was passed in
if (numstr+"" == "undefined" || numstr+"" == "null" || numstr+"" == "")
return false;
var isValid = true;
var decCount = 0; // number of decimal points in the string
// convert to a string for performing string comparisons.
numstr += "";
// Loop through string and test each character. If any
// character is not a number, return a false result.
// Include special cases for negative numbers (first char == '-')
// and a single decimal point (any one char in string == '.').
for (i = 0; i < numstr.length; i++) {
// track number of decimal points
if (numstr.charAt(i) == ".")
decCount++;
if (!((numstr.charAt(i) >= "0") && (numstr.charAt(i) <= "9") ||
(numstr.charAt(i) == "-") || (numstr.charAt(i) == "."))) {
isValid = false;
break;
} else if ((numstr.charAt(i) == "-" && i != 0) ||
(numstr.charAt(i) == "." && numstr.length == 1) ||
(numstr.charAt(i) == "." && decCount > 1)) {
isValid = false;
break;
}
//if (!((numstr.charAt(i) >= "0") && (numstr.charAt(i) <= "9")) ||
} // END for
return isValid;
} // end IsNum
Would I add it by typing this in the html directly under the first function rule:
if (IsNum(document.orderbooks.querySelectorAll("[name=postcode]")[0].value)) {
// Zip code is valid
} else {
alert("Postcode invalid! Please use only numbers:");
return false;
}
Is that how I would do this?
Two issues in your code:
Alert is missing double quotes.
The postcode value sent to IsValid4DigitZip is wrong.
Replace
document.orderbooks.Postcode.value
with
document.orderbooks.querySelectorAll("[name=postcode]")[0].value
Updated validate function code:
function validate(orderbooks) {
var digits = "0123456789"
var temp
if (IsValid4DigitZip(document.orderbooks.querySelectorAll("[name=postcode]")[0].value)) {
// Zip code is valid
} else {
alert("Invalid postcode:");
return false;
}
return true
}
function validate(orderbooks) {
var digits = "0123456789"
var temp
if (IsValid4DigitZip(document.orderbooks.querySelectorAll("[name=postcode]")[0].value)) {
// Zip code is valid
} else {
alert("Invalid postcode:");
return false;
}
return true
}
function IsValid4DigitZip(str) {
// Return immediately if an invalid value was passed in
if (str + "" == "undefined" || str + "" == "null" || str + "" == "")
return false;
var isValid = true;
str += "";
// Rules: zipstr must be 5 characters long, and can only contain numbers from
// 0 through 9
if ((str.trim().length != 4) || !isNumeric(str.trim()))
isValid = false;
return isValid;
} // end IsValid4DigitZip
//Check for numbers
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
<form name="orderbooks" onSubmit="return validate(orderbooks)">
Name: <input type="text" size="20" name="Name"> Street Number: <input type="text" size="5" name="streetnumber" maxlength="5"> Street Name: <input type="text" size="20" name="streetname" maxlength="25"> Postcode: <input type="text" size="4" name="postcode"
maxlength="4"> Telephone: <input type="text" size="11" name="telephone" maxlength="11"> Email: <input type="text" size="20"
name="email" maxlength="50">
<input type="reset" value="Clear the Form">
<input type="submit" value="Submit Form">
</form>

Javascript code won't work on my form [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am working on a form but my form is not working whenever I press submit. I am trying to evaluate whether sections of the form is empty, the email, and the number of digits for a user id. When I press submit nothing happens and I have been stuck like this for a while. FYI I have to use plain js and html.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Student Login Form</title>
<link rel='stylesheet' href='studentform.css' type='text/css' />
<script src="studentform.js"></script>
</head>
<body onload="document.form.studentid.focus();">
<h1>Student Login</h1>
<div class="container">
<form name="form" onsubmit="return validate();">
<label for="studentid">Student ID:</label>
<input type="number" name="studentid" maxlength="8" id="studentid" required />
<label for="name">Name:</label>
<input type="text" name="name" size="50" id="name" required />
<label for="email">Email:</label>
<input type="email" name="email" size="50" id="email" required />
<label for="emailconfirm">Email Confirmation:</label>
<input type="checkbox" name="emailconfirm" checked /><span>Send an email confirmation</span>
<select>
<option selected>Student Registration</option>
<option>Transcript</option>
</select>
<input type="submit" name="submit" value="Submit" />
</form>
</div>
`
Js.
function validate(){
var studentid = document.getElementById("studentid").value;
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
if(nameEmpty(name))
{
if(studentidEmpty(studentid))
{
if(emailEmpty(email))
{
if(digitCheck(studentid))
{
if checkEmail(email)
{
verify(name, studentid)
}
}
}
}
}
return false;
}
function studentidEmpty(studentid){
if ( studentid == "" ){
alert("Please provide your student id!");
studentid.focus();
return false;
}
}
function nameEmpty(name){
if ( name == "" ){
alert("Please provide your name!");
name.focus() ;
return false;
}
}
function emailEmpty(email){
if( email == "" ){
alert( "Please provide your email!" );
email.focus();
return false;
}
function digitCheck(studentid){
var ok = studentid.search(".{8,}");
if (ok!=0){
alert("Please provide ID with 8 digits.");
return false;
}
}
function checkEmail(email) {
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
}
function verify(name, studentid){
var personList = [["Joe",11111111],["Tammy",22222222],["Jones",33333333]];
for (list in personList) {
if (name in list && studentid in list){
alert("Welcome! An email verification with be sent soon.");
return true;
} else{
alert("Student Name and/or ID not found in records");
return false;
}
}
}
}
I think you should fix this line:
if checkEmail(email)
to
if (checkEmail(email))
you have forgotten the parentheses.
Edit:
I have completely fixed your code. Your errors:
you have forgotten to add else clauses for your field checkers, they were only returning false if the validation failed
your checking "if array contains value" was wrong, I have added a method from here
you were trying to focus on the values, not tags
you were trying to test email value from the "value of the value" not "value"
function validate() {
var studentid = document.getElementById("studentid").value;
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
if (nameEmpty(name)) {
if (studentidEmpty(studentid)) {
if (emailEmpty(email)) {
if (digitCheck(studentid)) {
if (checkEmail(email)) {
return verify(name, studentid);
}
}
}
}
}
return false;
}
function studentidEmpty(studentid) {
if (studentid == "") {
alert("Please provide your student id!");
document.getElementById("studentid").focus();
return false;
} else {
return true;
}
}
function nameEmpty(name) {
if (name == "") {
alert("Please provide your name!");
document.getElementById("name").focus();
return false;
} else {
return true;
}
}
function emailEmpty(email) {
if (email == "") {
alert("Please provide your email!");
document.getElementById("email").focus();
return false;
} else {
return true;
}
}
function digitCheck(studentid) {
var ok = studentid.search(".{8,}");
if (ok != 0) {
alert("Please provide ID with 8 digits.");
return false;
} else {
return true;
}
}
function checkEmail(email) {
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email)) {
alert('Please provide a valid email address');
email.focus;
return false;
} else {
return true;
}
}
function verify(name, studentid) {
var personList = [
["Joe", 11111111],
["Tammy", 22222222],
["Jones", 33333333]
];
for (list in personList) {
if (contains.call(list, name) && contains.call(list, studentid)) {
alert("Welcome! An email verification with be sent soon.");
return true;
}
}
alert("Student Name and/or ID not found in records");
return false;
}
var contains = function(needle) {
// Per spec, the way to identify NaN is that it is not equal to itself
var findNaN = needle !== needle;
var indexOf;
if(!findNaN && typeof Array.prototype.indexOf === 'function') {
indexOf = Array.prototype.indexOf;
} else {
indexOf = function(needle) {
var i = -1, index = -1;
for(i = 0; i < this.length; i++) {
var item = this[i];
if((findNaN && item !== item) || item === needle) {
index = i;
break;
}
}
return index;
};
}
return indexOf.call(this, needle) > -1;
};
<div>
<form>
<label for="name">Name:</label>
<input type="text" name="name" size="50" id="name" required />
<label for="studentid">Student ID:</label>
<input type="number" name="studentid" maxlength="8" id="studentid" required />
<label for="email">Email:</label>
<input type="email" name="email" size="50" id="email" required />
<label for="emailconfirm">Email Confirmation:</label>
<input type="checkbox" name="emailconfirm" checked /><span>Send an email confirmation</span>
<select>
<option selected>Student Registration</option>
<option>Transcript</option>
</select>
<input onclick="return validate();" type="submit" name="submit" value="Submit" />
</form>
</div>
Validate function always return false !! It shouldn't.
function validate(){
var studentid = document.getElementById("studentid").value;
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
return nameEmpty(name) && studentidEmpty(studentid) && emailEmpty(email) && digitCheck(studentid) && checkEmail(email) && verify(name, studentid);
}
Then be sure your form looks like :
<form name="form" onsubmit="return validate();" action="javascript:void(0)">
</form>
And your autofocus input to look like :
<input type="number" name="studentid" maxlength="8" id="studentid" required autofocus/>
You're forgetting the parentheses.
It is also wrong to start and end each function, try using the code below with these corrections.
function validate() {
var studentid = document.getElementById("studentid").value;
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
if (nameEmpty(name)) {
if (studentidEmpty(studentid)) {
if (emailEmpty(email)) {
if (digitCheck(studentid)) {
if (checkEmail(email)) {
verify(name, studentid)
}
}
}
}
}
return false;
}
function studentidEmpty(studentid) {
if (studentid == "") {
alert("Please provide your student id!");
studentid.focus();
return false;
}
}
function nameEmpty(name) {
if (name == "") {
alert("Please provide your name!");
name.focus();
return false;
}
}
function emailEmpty(email) {
if (email == "") {
alert("Please provide your email!");
email.focus();
return false;
}
}
function digitCheck(studentid) {
var ok = studentid.search(".{8,}");
if (ok != 0) {
alert("Please provide ID with 8 digits.");
return false;
}
}
function checkEmail(email) {
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
}
function verify(name, studentid) {
var personList = [
["Joe", 11111111],
["Tammy", 22222222],
["Jones", 33333333]
];
for (list in personList) {
if (name in list && studentid in list) {
alert("Welcome! An email verification with be sent soon.");
return true;
} else {
alert("Student Name and/or ID not found in records");
return false;
}
}
}

Javascript Phone number Format

It seems that my original question was closed out. I was able to complete most of the form validation requirement for my Pizza form. However now I'm just stuck at the phone number validation and format.
I need assistants for form validation for my phone number.
The phone number must be Numbers only with Dash for example 222-222-2222 and anything else besides that format or an empty field should cause an alert when I hit my submit button and doe snot allow the form to be submitted unless it is correct
Please review my code for document.PizzaForm.phone.value code for my pizza form I'm not sure how to edit the code to achieve my requirement.
<html>
<head>
<title>Hello and JavaScript</title>
<script>
function doClear()
{
document.PizzaForm.customer.value = "";
document.PizzaForm.address.value = "";
document.PizzaForm.city.value = "";
document.PizzaForm.state.value = "";
document.PizzaForm.zip.value = "";
document.PizzaForm.phone.value = "";
document.PizzaForm.email.value = "";
document.PizzaForm.sizes[0].checked = false;
document.PizzaForm.sizes[1].checked = false;
document.PizzaForm.sizes[2].checked = false;
document.PizzaForm.sizes[3].checked = false;
document.PizzaForm.toppings[0].checked = false;
document.PizzaForm.toppings[1].checked = false;
document.PizzaForm.toppings[2].checked = false;
document.PizzaForm.toppings[3].checked = false;
document.PizzaForm.toppings[4].checked = false;
document.PizzaForm.toppings[5].checked = false;
document.PizzaForm.toppings[6].checked = false;
document.PizzaForm.toppings[7].checked = false;
document.PizzaForm.toppings[8].checked = false;
return;
}
function doSubmit()
{
if (validateText()==false)
{
alert("Required data missing in Step 1");
}
if (validateRadio()==false)
{
alert("Required data missing in Step 2");
}
if(validateTops()==false)
{
alert("Required data missing in Step 3");
}
var OrderWindow
OrderWindow = window.open("","","status,height=500,width=500");
OrderWindow.focus();
with (OrderWindow.document)
{
write("<h1><center>Customer Order Summary</center></h1><p>")
write("Name:" + document.PizzaForm.customer.value + "<br>")
write("Address:" + document.PizzaForm.address.value + "<br>")
write("City:" + document.PizzaForm.city.value + "<br>")
write("State:" + document.PizzaForm.state.value + "<br>")
write("Zip Code:" + document.PizzaForm.zip.value + "<br>")
write("Phone Number:" + document.PizzaForm.phone.value + "<br>")
write("E-Mail:" + document.PizzaForm.email.value + "<br>")
write("Pizza Size:" + validateRadio() + "<br>")
write("Pizza Toppings:" + validateTops() + "<br>")
write("<h3><center>Thank You for your Order.</center></h3><p>")
}
return;
}
function validateText()
{
if (document.PizzaForm.customer.value == "")
{
alert("Please provide your name");
document.PizzaForm.customer.focus();
}
if (document.PizzaForm.address.value == "")
{
alert("Please provide your address.");
document.PizzaForm.address.focus();
}
if (document.PizzaForm.city.value == "")
{
alert("Please provide your City.");
}
if (document.PizzaForm.state.value == "")
{
alert("Please provide your State.");
}
if (document.PizzaForm.zip.value == "" ||
isNaN( document.PizzaForm.zip.value ) ||
document.PizzaForm.zip.value.length != 5 )
{
alert("Please provide your Zip code.");
document.PizzaForm.zip.focus() ;
}
if (document.PizzaForm.phone.value == "" ||
isNaN( document.PizzaForm.phone.value ) ||
document.PizzaForm.phone.value.length != 10 )
{
alert("Please provide your phone number.");
document.PizzaForm.phone.focus() ;
}
var emailID = document.PizzaForm.email.value;
atpos = emailID.indexOf("#");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct Email.")
document.myForm.Email.focus() ;
}
return (true);
}
function validateRadio()
{
if (document.PizzaForm.sizes[0].checked) true;
if (document.PizzaForm.sizes[1].checked) true;
if (document.PizzaForm.sizes[2].checked) true;
if (document.PizzaForm.sizes[3].checked) true;
return false;
}
function validateTops()
{
var sizes = document.PizzaForm.toppings;
var alert = ""
if (PizzaForm.toppings[0].checked) alert = "Pepperoni, " + alert;
if (PizzaForm.toppings[1].checked) alert = "Canadian Bacon, " + alert;
if (PizzaForm.toppings[2].checked) alert = "Sausage, " + alert;
if (PizzaForm.toppings[3].checked) alert = "Mushrooms, " + alert;
if (PizzaForm.toppings[4].checked) alert = "Pineapple, " + alert;
if (PizzaForm.toppings[5].checked) alert = "Black Olives, " + alert;
if (PizzaForm.toppings[6].checked) alert = "Extra Cheese, " + alert;
if (PizzaForm.toppings[7].checked) alert = "Plain, " + alert;
return alert;
}
</script>
</head>
<body>
<form Name ="PizzaForm">
<h1> The JavaScrpt Pizza Parlor</h>
<p>
<h4> Step 1: Enter your name, address, phone number, and email:</h4>
<font face="Courier New">
Name: <Input name="customer" size="50" type="text"><br>
Address: <Input name="address" size="50" type="text"><br>
City: <Input name="city" size="15"type="text">
State:<Input name="state" size="2"type="text"><br>
Zip: <Input name="zip" size="5"type="text"> <br>
Phone: <Input name="phone" size="50"type="text"><br>
Email: <Input name="email" size="31"type="text"><br>
</ font>
</ p>
<p>
<h4> Step 2: Select the size of pizza you want:</h4>
<font face="Courier New">
<input name="sizes" type="radio">Small
<input name="sizes" type="radio">Medium
<input name="sizes" type="radio">Large
<input name="sizes" type="radio">Jumbo<br>
</font>
</ p>
<p>
<h4> Step 3: Select the pizza toppings you want:</h4>
<font face="Courier New">
<input name="toppings" type="checkbox">Pepperoni
<input name="toppings" type="checkbox">Canadian Bacon
<input name="toppings" type="checkbox">Sausage<br>
<input name="toppings" type="checkbox">Mushrooms
<input name="toppings" type="checkbox">Pineapple
<input name="toppings" type="checkbox">Black Olives<br>
<input name="toppings" type="checkbox">Green Peppers
<input name="toppings" type="checkbox">Extra Cheese
<input name="toppings" type="checkbox">Plain
</ font>
</ p>
<input type="button" value="Submit Order" onClick="doSubmit()">
<input type="button" value="Clear Entries" onClick="doClear()">
</form>
</body>
</html>
The phone number must be Numbers only with Dash for example 222-222-2222
You can use a regex to check your phone number. This will match exactly 3 digits, a dash, 3 digits, a dash, and a final 4 digits.
var phone = "222-222-2222";
if (!/^\d{3}-\d{3}-\d{4}$/.test(phone)) {
console.log("bad number");
} else {
console.log("good number");
}
Then change your code to this:
if (!/^\d{3}-\d{3}-\d{4}$/.test(document.PizzaForm.phone.value)) {
alert("Please provide a correct phone number.");
document.PizzaForm.phone.focus();
}
If you are more flexible on your phone number format, for example allowing brackets around the area code, then please see below for more solutions:
http://www.regexplanet.com/advanced/javascript/index.html
https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch04s02.html
What about an alert for a blank field that says please enter phone number?
// This will treat empty strings, spaces and tabs as "empty"
function isEmpty(str){
return !str.replace(/^\s+/g, '').length;
}
if (isEmpty(document.PizzaForm.phone.value)) {
alert("Please enter a phone number.");
document.PizzaForm.phone.focus();
} else if (!/^\d{3}-\d{3}-\d{4}$/.test(document.PizzaForm.phone.value)) {
alert("Please provide a correct phone number.");
document.PizzaForm.phone.focus();
}
Assuming that's the pattern you want (xxx-xxx-xxxx), including the dashes, this works:
function validatePhone(ipt){
if(ipt.search('[0-9]{3}-[0-9]{3}-[0-9]{4}') === 0 && ipt.length === 12){
return true;
} else {
return false;
}
}
console.log(validatePhone('123-456-7890'));
console.log(validatePhone('abc-def-ghij'));
console.log(validatePhone('123-456-789'));
Of course, leave out the testing code.
I actually recommend letting them use dashes, slashes, or whatever, then just parsing them out:
window.verify = function() {
var phone = document.getElementById("phone").value.split("");
var verified = "";
for (var char in phone)
{
verified += parseInt(phone[char]) >= 0 ? phone[char] : "";
}
var len = verified.length;
if (len != 7 && len != 10)
{
alert("Invalid number of digits!");
}
else
{ // then format the resulting number as you see fit
var finalNum = "";
if (len == 10)
{
finalNum += verified.substring(0,3) + "-"
verified = verified.substring(3);
}
finalNum += verified.substring(0,3) + "-";
verified = verified.substring(3);
finalNum += verified;
alert(""+finalNum);
}
}
<input type="text" id="phone" />
<br>
<br>
<button type="button" onclick="verify()">Validate Phone</button>

JavaScript form validation for first name, last name and email address is displaying nothing

I am just copying my code:
HTML
<form id='test'>
Name *
<input id="lname" type="text"><span id="wronglname" class="error">*This is a required field</span>
Name *
<input id="name" type="text"><span id="wrongname" class="error">*This is a required field</span>
Email*
<input id="email" type="text"><span id="wrongemail" class="error">* Wrong Email Address</span>
<div>
<input type="submit" value="Submit">
</div>
</form>
Javascript
function ValidateForm() {
var hasError = false;
if (document.getElementById('lname').value == "") {
document.getElementById('lwrongname').style.display = "inline";
hasError = true;
} else {
document.getElementById('wrongname').style.display = "none";
}
if (document.getElementById('name').value == "") {
document.getElementById('wrongname').style.display = "inline";
hasError = true;
} else {
document.getElementById('wrongname').style.display = "none";
}
if (document.getElementById('email').value.search(/^[a-zA-Z]+([_\.-]?[a-zA-Z0-9]+)*#[a-zA-Z0-9]+([\.-]?[a-zA-Z0-9]+)*(\.[a-zA-Z]{2,4})+$/) == -1) {
document.getElementById('wrongemail').style.display = "inline";
hasError = true;
} else {
document.getElementById('wrongemail').style.display = "none";
}
return !hasError;
}
document.getElementById('test').onsubmit = ValidateForm;
CSS
.error {
display:none;
color:red;
}
I am getting no response at all, and whenever I check javascript console by chrome, it shows me also no error, I am not too sure what's wrong with my coding, can anyone help me out?
Here is your mistake:
if (document.getElementById('lname').value == "") {
document.getElementById('lwrongname').style.display = "inline";
hasError = true;
}
Notice document.getElementById('lwrongname'), should be document.getElementById('wronglname').

Javascript - Value not passing to function

So I have this form:
<form name="login" id="login" action="" method="POST" onSubmit="return test()">
<input type="text" size="10" name="username" /><div id="wrongUser"></div>
<br />
<input type="password" size="10" name="password" /><div id="wrongPass"></div>
<br />
<input type="submit" value="submit" name="submit" /><br /><br />
</form>
and these two functions:
function test()
{
var user = document.login.username.value;
var pass = document.login.password.value;
if((user == "" || user == null) && (pass == "" || pass == null))
{
document.getElementById('wrongUser').innerText = "Please Enter Username";
document.getElementById('wrongPass').innerText = "Please Enter Password";
return false;
}
if(checkEmpty(user, 'wrongUser', "Please Enter Username"))
return false
if(checkEmpty(pass, 'wrongPass', "Please Enter Password"))
return false;
return true;
}
function checkEmpty(name, id, output)
{
if(name == "" || name == null)
{
document.getElementById(id).innerText = "";
document.getElementById(id).innerText = output;
return true;
}
else
return false;
}
Now the functions kinda work but not how I would think. If the user only doesn't enter anything (first time) then they get the 2 errors. If the user enter just a username (second time) then the username error should disappear, but it doesn't. If I take it out of the function and replace the variables with their normal values then it works just fine. Why would it change when put in this function?
Put the document.getElementById().innerText = '' in the else, not in the if. Because you only reset the innerText when it's empty, but you would like to reset the tekst if it's not empty:
function checkEmpty( name, id, output ) {
var elem = document.getElementById(id); // it's faster to put the element in a var
if( name === undefined || name == '' name == null )
elem.innerText = output;
return true;
else
elem.innerText = '';
return false;
}

Categories