how do i make a verifier for my html form? - javascript

<div class="entry-container row">
<div class="signup containerss col">
<h1 class="center">New Here,</h1>
<h3 class="center">Signup Here</h3>
<form action="signup" class="form-inside" method='post'>
username<input type='text' name='Username' required/><br>
password<input type="text" name='Password' required/><br>
Firstname<input type="text" name='Fname' required/><br>
Lastname<input type="text" name='Lname' required/><br>
Date Of Birth<br><input type="date" name='DOB' required/><br>
Email<input type="text" name='Email' required/><br>
<input type='submit' name='Submit'/>
</form>
</div>
<div class="login float-right col" style="height: 300px;">
<h1 class="center">Already a Member</h1>
<h3 class="center">Login Here</h3>
<form action="login" class="form-inside" method='POST'>
username<input type='text' name='User' required/><br>
password<input type='text' name='Pass' required/>
<input type="submit" name='submit'>
</form>
</div>
<div>
here is a simple form for login or signup,
now what I want to do is i want to make a js code that verifies if the username is a string(has no special chars), password is strong enough, email is valid etc, and if everything is perfect ,only then the user must be allowed to submit the form,
if not then I want to tell the mistakes yo the user, while the user is typing
how can I achieve this.
2 question i want answer to ,
1
I had tried this,
<div class='hide' onclick='showerror()' id='error'>error</div>
<style>.hide{display:none;}</style>
<script>function showerror(){
var error= document.getelementbyid('error')
error.Classlist.toggle('hide')
}</script>
how can i call this same function when the user is typing ,
2
how can i use regex in js to verify if the textontext of a element is string or not.

You can use javascript event for validating form.
function ValidateForm()
{
var inputText1 = document.form1.text1;
var inputText2 = document.form1.text2;
var inputText3 = document.form1.text3;
//add other elements validation here
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(inputText.value.match(mailformat))
{
document.form1.text1.focus();
return true;
}
else
{
alert("You have entered an invalid email address!");
document.form1.text1.focus();
return false;
}
}
HTML
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript form validation - checking email</title>
<link rel='stylesheet' href='form-style.css' type='text/css' />
</head>
<body onload='document.form1.text1.focus()'>
<div class="mail">
<h2>Input an email and Submit</h2>
<form name="form1" action="#">
<ul>
<li><input type='text' name='text1'/></li>
<li><input type='password' name='text2'/></li>
<li><input type='text' name='text3'/></li>
<li> </li>
<li class="submit"><input type="submit" name="submit" value="Submit" onclick="ValidateForm()"/></li>
<li> </li>
</ul>
</form>
</div>
<script src="email-validation.js"></script>

Related

Javascript sign up function

Here, I am trying to use the signUp() function to get the users details and store them into the database. I already tested the backend Javascript file (signUp function) using postman and it works perfectly fine.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<link href="css\signup.css" rel="stylesheet" type="text/css">
<script>
function signUp() {
if (document.getElementById("password2").value == document.getElementById("cfmpassword2").value) {
var users = new Object();
users.firstName = document.getElementById("firstName").value;
users.lastName = document.getElementById("lastName").value;
users.username2 = document.getElementById("username2").value;
users.email = document.getElementById("email").value;
users.password2 = document.getElementById("password2").value;
var postUser = new XMLHttpRequest(); // new HttpRequest instance to send user details
postUser.open("POST", "/users", true); //Use the HTTP POST method to send data to server
postUser.setRequestHeader("Content-Type", "application/json");
// Convert the data in "users" object to JSON format before sending to the server.
postUser.send(JSON.stringify(users));
}
else {
alert("Password column and Confirm Password column doesn't match!")
}
}
</script>
</head>
<body>
<div style="margin-top: -703px; margin-left: 1250px; position: absolute;">
<!-- Sign up button -->
<p>Need an account?
<button class="signup" id='signup' onclick="document.getElementById('id02').style.display='block'" style="width:auto; height: 6.1vh;">
Sign Up
</button>
</p>
</div>
<!-- The Sign Up Modal-->
<div id="id02" class="modal2">
<span onclick="document.getElementById('id02').style.display='none'" class="close2" title="Close Modal">×</span>
<!-- Modal Content -->
<form class="modal-content2">
<div class="container3">
<h1>Sign Up</h1>
<p>Please fill in this form to create an account.</p>
<hr>
<label for="firstName"><b>First Name</b></label>
<input type="text" id="firstName" placeholder="Enter First Name" name="firstName" required>
<label for="lastName"><b>Last Name</b></label>
<input type="text" id="lastName" placeholder="Enter Last Name" name="lastName" required>
<label for="username"><b>Username</b></label>
<input type="text" id="username2" placeholder="Enter Username" name="username" required>
<label for="email"><b>Email</b></label>
<input type="text" id="email" placeholder="Enter Email" name="email" required>
<label for="psw"><b>Password</b></label>
<input type="password" id="password2" placeholder="Enter Password" name="psw" required>
<label for="psw-confirm"><b>Confirm Password</b></label>
<input type="password" id="cfmpassword2" placeholder="Confirm Password" name="psw-confirm" required>
<br>
<br>
<p>By creating an account you agree to our <a href="aboutus.html" style="color:dodgerblue">Terms &
Privacy</a>.</p>
<div class="clearfix">
<button type="button" onclick="document.getElementById('id02').style.display='none'" class="cancelbtn2">Cancel</button>
<button type="submit" class="signupbtn" onclick="signUp()">Sign Up</button>
</div>
</div>
</form>
</div>
</body>
</html>
If Confirm Password matches Password, I will get the user details and send the data to my database server. Else, an alert msg is supposed to pop up.
However, I after trying it out, I see nothing being added into my database. My else part works though, an alert message does pop up on my browser.
Is this due to an error about the Confirm Password? Because I have a very similar set of working codes except that it doesn't contain the Confirm Password column. I got the confirm password from here how to check confirm password field in form without reloading page
Could someone please help identify the problem? Thanks a lot!
You are calling signUp() when a submit button is clicked.
The JavaScript runs, but as the XHR request is being prepared, the form is submitted, the browser navigates, and the XHR request is canceled.
Don't use a submit button if you aren't submitting the form.
Your comment that changing the submit to a regular button prevents you from actually being able to click it seems a little odd. The below code has a standard button and seems OK which suggests a css issue perhaps. I tested this with a php endpoint and the request was sent OK so it ought to be find hitting your javascript endpoint - unless there is another factor (css most likely ) interfering with the button
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<link href="css/signup.css" rel="stylesheet" type="text/css">
<script>
function signUp(event) {
event.preventDefault();
if (document.getElementById("password2").value == document.getElementById("cfmpassword2").value) {
var users = new Object();
users.firstName = document.getElementById("firstName").value;
users.lastName = document.getElementById("lastName").value;
users.username2 = document.getElementById("username2").value;
users.email = document.getElementById("email").value;
users.password2 = document.getElementById("password2").value;
var postUser = new XMLHttpRequest();
/*
Optional:
A callback to process response from the server and possibly manipulate the DOM
or let the user know if things went OK.
*/
postUser.onreadystatechange=function(){
if( this.status==200 && this.readyState==4 ){
alert( this.response )
}
}
postUser.open( "POST", "/users", true );
postUser.setRequestHeader( "Content-Type", "application/json" );
postUser.send( JSON.stringify( users ) );
}
else {
alert("Password column and Confirm Password column doesn't match!")
}
}
</script>
</head>
<body>
<div style="margin-top: -703px; margin-left: 1250px; position: absolute;">
<!-- Sign up button -->
<p>Need an account?
<button class="signup" id='signup' onclick="document.getElementById('id02').style.display='block'" style="width:auto; height: 6.1vh;">
Sign Up
</button>
</p>
</div>
<!-- The Sign Up Modal-->
<div id="id02" class="modal2">
<span onclick="document.getElementById('id02').style.display='none'" class="close2" title="Close Modal">×</span>
<!-- Modal Content -->
<form class="modal-content2">
<div class="container3">
<h1>Sign Up</h1>
<p>Please fill in this form to create an account.</p>
<hr>
<label for="firstName"><b>First Name</b></label>
<input type="text" id="firstName" placeholder="Enter First Name" name="firstName" required>
<label for="lastName"><b>Last Name</b></label>
<input type="text" id="lastName" placeholder="Enter Last Name" name="lastName" required>
<label for="username"><b>Username</b></label>
<input type="text" id="username2" placeholder="Enter Username" name="username" required>
<label for="email"><b>Email</b></label>
<input type="text" id="email" placeholder="Enter Email" name="email" required>
<label for="psw"><b>Password</b></label>
<input type="password" id="password2" placeholder="Enter Password" name="psw" required>
<label for="psw-confirm"><b>Confirm Password</b></label>
<input type="password" id="cfmpassword2" placeholder="Confirm Password" name="psw-confirm" required>
<br>
<br>
<p>By creating an account you agree to our Terms & Privacy.</p>
<div class="clearfix">
<button type="button" onclick="document.getElementById('id02').style.display='none'" class="cancelbtn2">Cancel</button>
<!--
modify the button to a standard button rather than a submit
- this enables the ajax function to do what is intended.
An alternative would be to invoke `event.preventDefault()` within
the signUp(event) function to stop the submit button from actually
submitting the form
-->
<button type="button" class="signupbtn" onclick="signUp(event)">Sign Up</button>
</div>
</div>
</form>
</div>
</body>
</html>

How to tie radio button with input text fields?

This is a sign up form for an employee. The employee has to check in a radio button if he is temporary or permament. If temporary he should fill the input contract number and if permament the hiring date. How can I bind the radio button with the input so that he cannot "cross-complete" , for example fill the hiring date if he is temporary. I want to enable him to fill out each input only if he has pressed that specific radio button.
php code :
<?php include 'dbconfig.php';?>
<?php header('Content-Type: text/html; charset=utf-8');?>
<!DOCTYPE HTML PUCLIC "-//W3C//DTDHTML
4.0 Transitional//EN"><HTML>
<HEAD>
<link rel="stylesheet" type="text/css" href="logintest.css">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</HEAD>
<button class="btn" TYPE="submit" name="goback" onclick="window.location.href='login.php'">Go Back </button>
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
if(isset($_POST['submit']))
{
$sql = "INSERT INTO employee (empID,EFirst,ELast,username, passcode)
VALUES ('".$_POST["empID"]."','".$_POST["EFirst"]."','".$_POST["ELast"]."','".$_POST["username"]."','".$_POST["passcode"]."')";
$result = mysqli_query($conn,$sql);
$answer=$_POST['kind'];
if($answer='permament'){
$sql1 = "INSERT INTO permament_employee (empID,Hiring_Date) VALUES ('".$_POST["empID"]."','".$_POST["date"]."')";
$result1 = mysqli_query($conn,$sql1);
}
if ($answer='temporary'){
$sql2= "INSERT INTO temporary_employee(empID) VALUES ('".$_POST["empID"]."')";
$result2 = mysqli_query($conn,$sql2);
}
echo "<script> location.replace('login.php') </script>";
}
?>
<FORM METHOD="post" ACTION="">
<div class="input-group">
<label>id</label>
<INPUT TYPE="text" name="empID" SIZE="30" required>
</div>
<div class="input-group">
<label>First Name</label>
<INPUT TYPE="text" name="EFirst" SIZE="30" required>
</div>
<div class="input-group">
<label>Last Name</label>
<INPUT TYPE="text" name="ELast" SIZE="30" required>
</div>
<div class="input-group">
<label>username</label>
<INPUT TYPE="text" name="username" SIZE="30" required>
</div>
<div class="input-group">
<label>password</label>
<INPUT TYPE="password" name="passcode" SIZE="30" required>
</div>
<div class="input-group">
<div class="some-class">
<label> Permament <input type="radio" name="kind" value="permament" id="permament" required> <br> <input type="date" name="date" value="date" id="date" required> <br> </label>
<label> Temporary <input type="radio" name="kind" value="temporary" id="temporary" required> <br> <input type="number" name="ContractNr" value="ContractNr" id="ContractNr" placeholder="Contract Number" required> <br> </label>
</div>
</div>
<br>
<br>
<br>
<br>
<button class="btn" TYPE="submit" name="submit">Submit Info </button>
<button class="btn" TYPE="reset" name="Reset">Reset </button>
</FORM>
</HTML>
You need javascript.
You have to bind a 'change' event on your radio buttons, and set visibility of your inputs according to radio button selected value.
If you are using jQuery you could add the following :
<script>
$(‘input[name=“kind”]’).change(function(){
if($(this).val() == ‘temporary’){
$(‘input[name=“date”]).hide();
$(‘input[name=“ContractNr”]).show();
}else{
$(‘input[name=“date”]).show();
$(‘input[name=“ContractNr”]).hide();
}
});
</script>
Or if you just want to disable :
<script>
$(‘input[name=“kind”]’).change(function(){
if($(this).val() == ‘temporary’){
$(‘input[name=“date”]).prop(‘disabled’, true);
$(‘input[name=“ContractNr”]).prop(‘disabled’, false);
}else{
$(‘input[name=“date”]).prop(‘disabled’, false);
$(‘input[name=“ContractNr”]).prop(‘disabled’, true);
}
});
</script>

javascript checking for blank for phonenumber and address

Please help me, I'm stuck.
Why doesn't the JavaScript below work? The script is checking if phone number and address is empty, but when the phone number and address field is entered, the alert still pops out.
const order = document.getElementById("orderInput");
const main = document.getElementById("main");
const phone = document.getElementById("phoneNumberInput").value;
const address = document.getElementById("addressInput").value;
function checkingIsEmpty() {
if (phone == ''){
alert("Please insert your phone number");
return false;
}
if (address ==''){
alert("Please insert your address");
return false;
}
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>checking form is empty</title>
</head>
<body>
<form class="" action="index.html" method="post" onsubmit="return checkingIsEmpty()">
<div id="message">
<label>
<textarea name="messageInput" rows="2" cols="40" placeholder="add message..."></textarea>
</label>
</div>
<div id="phoneNumber">
<input id="phoneNumberInput" type="number" name="phone" value="" placeholder="Please input your phonenumber">
</div>
<div id="address">
<input id="addressInput" type="text" name="address" placeholder="your address here" size= "50px" value="" >
</div>
<div id="order">
<input id="orderInput" type="submit" name="description" value="order" min='0'> <p></p>
</div>
<div id= "reset">
<input type="reset" name="" value="RESET">
</div>
</form>
<script src="app.js" charset="utf-8"></script>
</body>
</html>
I'd agree with #Madara's comment, that you should... just add required attribute on form inputs which are required and let the browser do the work for you
However, I believe the reason your code is not working is because you appear to be setting the const values of phone and address on entry to the screen... and then you're checking that initial value (rather than the latest value).
Instead you need to get the latest value from the controls as part of the function...
function checkingIsEmpty(){
if (document.getElementById("phoneNumberInput").value == ''){
alert("Please insert your phone number");
return false;
}
if (document.getElementById("addressInput").value ==''){
alert("Please insert your address");
return false;
}
return true;
}
(Minor edit, you also need to return true at the end of your function, otherwise your submit won't work)
simplest way is to check if (!phoneInput.value) { ... }
as empty string and null will return falsy value
The problem you are having is because you are assigning the value of the fields at the time the page loads. Not at the time the function is called on submit. If you move the variable assignment into the function it should work for you.
const order = document.getElementById("orderInput");
const main = document.getElementById("main");
function checkingIsEmpty(){
const phone = document.getElementById("phoneNumberInput").value;
const address = document.getElementById("addressInput").value;
if (phone == ''){
alert("Please insert your phone number");
return false;
}
if (address ==''){
alert("Please insert your address");
return false;
}
return false;//for the example I don't want it to submit
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>checking form is empty</title>
</head>
<body>
<form class="" action="index.html" method="post" onsubmit="return checkingIsEmpty()">
<div id="message">
<label>
<textarea name="messageInput" rows="2" cols="40" placeholder="add message..."></textarea>
</label>
</div>
<div id="phoneNumber">
<input id="phoneNumberInput" type="number" name="phone" value="" placeholder="Please input your phonenumber">
</div>
<div id="address">
<input id="addressInput" type="text" name="address" placeholder="your address here" size= "50px" value="" >
</div>
<div id="order">
<input id="orderInput" type="submit" name="description" value="order" min='0'> <p></p>
</div>
<div id= "reset">
<input type="reset" name="" value="RESET">
</div>
</form>
<script src="app.js" charset="utf-8"></script>
</body>
</html>
You need to include the document.getElementById in your conditionals. Also, I would wrap both conditionals (Phone and Address) in another conditional so you can add classes for error styling on errored fields.
const order = document.getElementById("orderInput");
const main = document.getElementById("main");
var phone = document.getElementById("phoneNumberInput").value;
var address = document.getElementById("addressInput").value;
function checkingIsEmpty(){
if (document.getElementById("phoneNumberInput").value == '' || document.getElementById("addressInput").value == '') {
if (document.getElementById("phoneNumberInput").value == ''){
alert("Please insert your phone number");
return false;
}
if (document.getElementById("addressInput").value == ''){
alert("Please insert your address");
return false;
}
} else {
alert('success');
}
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>checking form is empty</title>
</head>
<body>
<form class="" action="index.html" method="post" onsubmit="return checkingIsEmpty()">
<div id="message">
<label>
<textarea name="messageInput" rows="2" cols="40" placeholder="add message..."></textarea>
</label>
</div>
<div id="phoneNumber">
<input id="phoneNumberInput" type="number" name="phone" value="" placeholder="Please input your phonenumber">
</div>
<div id="address">
<input id="addressInput" type="text" name="address" placeholder="your address here" size= "50px" value="" >
</div>
<div id="order">
<input id="orderInput" type="submit" name="description" value="order" min='0'> <p></p>
</div>
<div id= "reset">
<input type="reset" name="" value="RESET">
</div>
</form>
<script src="app.js" charset="utf-8"></script>
</body>
</html>
The values of inputs are stored inside a constant, not a variable.
When page is loaded, the script is executed and the contents of actual inputs are stored.
When you're calling checkingIsEmpty() the values aren't refreshed.
I suggest you to get the value inside the checkingIsEmpty() function if you want to keep checking with javascript, but as suggested Madara in comments, you can use the required attribute <input id="phoneNumberInput" type="number" name="phone" value="" placeholder="Please input your phonenumber" required>.
Checking inputs with required attribute or javascript is nice, but you have to check it server-side too. It's easy to press F12 and edit dom.
function checkingIsEmpty()
{
let phone = document.getElementById("phoneNumberInput").value;
let address = document.getElementById("addressInput").value;
if (phone == '')
{
alert("Please insert your phone number");
return (false);
}
if (address == '')
{
alert("Please insert your address");
return (false);
}
return (true); //You forgot to return true in case of your form is validated
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>checking form is empty</title>
</head>
<body>
<form class="" action="index.html" method="post" onsubmit="return checkingIsEmpty()">
<div id="message">
<label>
<textarea name="messageInput" rows="2" cols="40" placeholder="add message..."></textarea>
</label>
</div>
<div id="phoneNumber">
<input id="phoneNumberInput" type="number" name="phone" value="" placeholder="Please input your phonenumber">
</div>
<div id="address">
<input id="addressInput" type="text" name="address" placeholder="your address here" size= "50px" value="" >
</div>
<div id="order">
<input id="orderInput" type="submit" name="description" value="order" min='0'> <p></p>
</div>
<div id= "reset">
<input type="reset" name="" value="RESET">
</div>
</form>
<script src="app.js" charset="utf-8"></script>
</body>
</html>

Forn Validation ignored with AJAX call

I have a form that uses an AJAX call to submit the info to Google Sheets which is working fine except when I try to add form validation. Then it is just running the AJAX call.
Below is my HTML Form:
<!DOCTYPE html>
<html class="no-js" lang="en">
<head>
<title>MooWoos Stall Booking</title>
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway:400,800">
<link rel='stylesheet' href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<!--build:css css/styles.min.css-->
<link rel="stylesheet" href="/css/bootstrap.css">
<link rel="stylesheet" href="/css/style.css">
<!--endbuild-->
</head>
<body>
<!-- Page Content -->
<div class="container">
<nav class="navbar navbar-toggleable-md navbar-light">
<a class="logo"><img src="assets/logo_opt.png"></a>
</nav>
<hr>
<div class="modal fade" id="redirect_page" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="form-horizontal">
<div class="modal-body">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<div id="user_msg" align="left">Booking successful! Redirecting to PayPal... </div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 col-md-offset-3 bookingform">
<h1>Stall Booking Form</h1>
<p class="lead">
Fill out the form to book and pay for your stall!
</p>
<form id="bookingForm">
<div class="form-group">
<label for="name">Name: </label>
<input type="text" name="name" class="form-control" placeholder="Your Name" value="" title="Please enter your name" required/>
</div>
<div class="form-group">
<label for="address">Address: </label>
<textarea name="address" class="form-control" placeholder="Your Address" value="" title="Please enter your address"></textarea>
</div>
<div class="form-group">
<label for="phone">Telephone Number: </label>
<input type="text" name="phone" class="form-control" placeholder="Your Telephone Number" value="" title="Please enter the best telephone number to contact you on"/>
</div>
<div class="form-group">
<label for="email">Email: </label>
<input type="text" name="email" class="form-control" placeholder="Your Email" value="" title="Please enter your Email address"/>
</div>
<div class="form-group">
<label for="date">Which date would you like to book?: </label>
<p><input type="radio" name="date" value="13th September" /> Sunday 13th September</p>
<p><input type="radio" name="date" value="6th February" /> Saturday 6th February</p>
</div>
<div class="form-group">
<label>What type of stall do you require?</label>
<div>
<input type="radio" name="stallType" id="stallType-Preloved" value="Preloved">
<label for="stallType-Preloved">Preloved</label>
<div class="reveal-if-active">
<label for="c-rail">Will you be bringing a clothes rail?: </label>
<input type="radio" name="c-rail" value="Yes" /> Yes
<input type="radio" name="c-rail" value="No" /> No
</div>
</div>
<div>
<input type="radio" name="stallType" id="stallType-Craft" value="Craft">
<label for="stallType-Craft">Craft</label>
<div class="reveal-if-active">
<label for="craftName">What name do you use?</label>
<input type="text" id="craftName" name="craftName" class="require-if-active" placeholder="Craft Name" title="Please provide us with your Craft name" value="" />
</div>
</div>
<div>
<input type="radio" name="stallType" id="stallType-Business" value="Business">
<label for="stallType-Business">Business</label>
<div class="reveal-if-active">
<label for="bizName">What is your business name?</label>
<input type="text" id="bizName" name="bizName" class="require-if-active" placeholder="Business Name" title="Please provide us with your Business name" value="" />
<label for="insurance">Do you have Public Liability Insurance?</label>
<input type="radio" id="insurance" name="insurance" class="require-if-active" data-require-pair="#stallType-Business" title="We will require proof of this prior to market day" value="Yes"/> Yes
<input type="radio" id="insurance" name="insurance" class="require-if-active" data-require-pair="#stallType-Business" title="Our insurance does not cover other businesses. Please ensure you have adequate cover and provide us with proof prior to market day" value="No"/> No
</div>
</div>
</div>
<input type="button" id="submit-form" class="btn btn-success btn-lg" value="Book & Pay" />
</form>
</div>
</div>
<!-- /.row -->
<hr>
<!-- Footer -->
<footer>
<div class="row">
<div class="col-lg-12">
<p>Copyright © MooWoos 2018. Website by Luke Brewerton</p>
</div>
</div>
<!-- /.row -->
</footer>
</div>
<!-- /.container -->
<!--build:js js/mwbookings-min.js -->
<script src="js/jquery.min.js"></script>
<script src="js/tether.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery.serialize-object.min.js"></script>
<script src="js/main.js"></script>
<!-- endbuild -->
</body>
</html>
And my JS file:
var $form = $('form#bookingForm'),
url = 'https://script.google.com/macros/s/AKfycbwaEsXX1iK8nNkkvL57WCYHJCtMAbXlfSpSn3rsJj2spRi-41Y/exec'
function validateForm() {
var errorMessage="";
var name=document.forms["bookingForm"]["name"].value;
if (name==null ||name==""){
errorMessage = "Your Name is required.\
";
}
if (errorMessage !=""){
alert(errorMessage);
return false;
}
}
$('#submit-form').on('click', function(e) {
//e.preventDefault();
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "json",
data: $form.serializeObject(),
success: function () {
$('#redirect_page').modal('show');
window.setTimeout(function(){location.reload()},3000);
}
});
});
I have a sneaky feeling that I need to do my form validation within the submit function before the AJAX call but I am new to using JS to do this, previously I have used PHP to do it all.
The main issue is that you aren't calling the validateForm() function anywhere. You need to call that before the form is submit in order to check its validity.
You should also use a type="submit" button within your form for accessibility reasons. This will also allow users to submit the form by pressing the return key while a field is in focus. You can then hook to the submit event to handle the form submission. Try this:
<form id="bookingForm">
<!-- form fields... -->
<input type="submit" id="submit-form" class="btn btn-success btn-lg" value="Book & Pay" />
</form>
function validateForm() {
var errorMessage = "";
var name = $('input[name="name"]').val();
if (name == null || name == "") {
errorMessage = "Your Name is required.\n";
}
return errorMessage;
}
$form.on('submit', function(e) {
e.preventDefault();
var error = validateForm();
if (error) {
alert(error);
return;
}
var jqxhr = $.ajax({
// ajax request...
});
});
You should however note that in most browsers the required attribute will achieve this logic for you without the need for any JS intervention.
var $form = $('form#bookingForm'),
url = 'https://script.google.com/macros/s/AKfycbwaEsXX1iK8nNkkvL57WCYHJCtMAbXlfSpSn3rsJj2spRi-41Y/exec'
function validateForm() {
var errorMessage="";
var name=document.forms["bookingForm"]["name"].value;
if (name==null ||name==""){
errorMessage = "Your Name is required.\
";
return true;
}
if (errorMessage !=""){
alert(errorMessage);
return false;
}
}
$('#submit-form').on('click', function(e) {
//e.preventDefault();
var res = validateForm();
if(res != false) {
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "json",
data: $form.serializeObject(),
success: function () {
$('#redirect_page').modal('show');
window.setTimeout(function(){location.reload()},3000);
}
});
} else {
//handle else condition however u want
}
});

Must Check box to submit form

Trying to create a form that will force people to select the checkbox with the phrase "I accept the terms and conditions" in order to send the form.
This is what I have but it is not submitting the form — I get an error.
Javascript that I have placed in the header:
<script type="text/javascript">
<!--
function validate_form ( )
{
valid = true;
if ( document.form1.cb.checked == false )
{
alert ( "Please check the Terms & Conditions box ." );
valid = false;
}
return valid;
}
//-->
</script>
Form:
<form action="/cgi-bin/FormMail.pl" method="POST" name="frmOne" id="frmOne">
<input type=hidden name="recipient" value="XXX#XXX.com"/>
<table width="100%" cellspacing="5" cellpadding="5" style="margin-top:-20px">
<tr>
<td width="50%" valign="top">
<br/>
<p><span id="sprytextfield1">
<label for="Full Name">Full Name (First and Last): </label>
<input name="Full Name" type="text" id="name" tabindex="10" size="60" />
<span class="textfieldRequiredMsg"><br />Please provide information.</span></span> </p>
<p><span id="sprytextfield2">
<label for="Your Email">Your e-mail address: </label>
<input name="email" type="text" id="email" size="60" />
<span class="textfieldInvalidFormatMsg"></span></span> </p>
<p><span id="sprytextfield3">
<label for="Phone Number"> Phone Number: </label>
<input name="Phone Number" type="text" id="phone" size="60" />
<span class="textfieldInvalidFormatMsg"><br />Invalid format.</span><span class="textfieldRequiredMsg"><br/>A phone number is required.</span></span></p>
<p class="text">
<span id="sprytextfield4">
<label for="Nature Of The Accident">Nature of Accident, i.e. slip and fall, motor vehicle accident, etc.: </label>
<input name="Nature Of The Accident" type="text" id="natureOfAccident" size="60" />
</span></p>
<p><span id="sprytextfield5">
<label for="Date Of The Accident">Date of the Accident: </label>
<input name="Date Of The Accident" type="text" id="dateOfAccident" size="60" />
<span class="textfieldRequiredMsg"><br />Please provide information.</span><span class="textfieldInvalidFormatMsg"><br />Invalid format.</span></span></p>
<p class="text">
</td>
<td width="50%" valign="top">
<p class="text">
<span id="sprytextarea1">
<label for="Description Of The Injury"><br />Brief Description of your Injuries: </label>
<textarea name="Description Of The Injury" cols="45" rows="4" id="descriptionOfInjury">
</textarea>
<span class="textareaRequiredMsg"><br />Please provide information.</span></span></p>
<p class="text">
<span id="sprytextarea2">
<label for="Description Of The Accident">Brief Description of the Accident:</label>
<textarea name="Description Of The Accident" id="descriptionOfAccident" cols="45" rows="4"></textarea>
<span class="textareaRequiredMsg"><br />
Please provide information.</span></span></p>
<p class="text">
<span id="sprytextfield6">
<label for="How Did You Hear About Us">How did you hear about us?: </label>
<input name="How Did You Hear About Us" type="text" id="howDidYouHear" size="56" />
<span class="textfieldRequiredMsg"><br />Please provide information.</span></span> </p>
<input type="checkbox" name="agree" value="agree_terms" id="disclaimer" />
<label for="disclaimer">I have read the Disclaimer</label>
<br/><br />
<input type="reset" name="reset" id="reset" value="Reset Form" />
<input type="submit" name="Form Action" id="send" tabindex="100" value="Submit" />
</td>
</tr>
</table>
</form>
<script type="text/javascript">
<!--
var sprytextfield1 = new Spry.Widget.ValidationTextField("sprytextfield1", "none", {validateOn:["blur", "change"]});
var sprytextfield2 = new Spry.Widget.ValidationTextField("sprytextfield2", "email", {validateOn:["blur", "change"], isRequired:false});
var sprytextfield3 = new Spry.Widget.ValidationTextField("sprytextfield3", "phone_number", {validateOn:["blur"], useCharacterMasking:true});
var sprytextfield4 = new Spry.Widget.ValidationTextField("sprytextfield4", "none", {isRequired:false, validateOn:["blur", "change"]});
var sprytextfield5 = new Spry.Widget.ValidationTextField("sprytextfield5", "date", {hint:"dd/mm/yyyy", validateOn:["blur", "change"], format:"dd/mm/yyyy"});
var sprytextarea1 = new Spry.Widget.ValidationTextarea("sprytextarea1", {validateOn:["blur", "change"]});
var sprytextarea2 = new Spry.Widget.ValidationTextarea("sprytextarea2", {validateOn:["blur", "change"]});
var sprytextfield6 = new Spry.Widget.ValidationTextField("sprytextfield6", "none", {validateOn:["blur", "change"], hint:"Google, etc"});
//-->
</script></div>
You are referencing the form and elements wrong, try something like this:
<form name="frmOne" method="POST" onSubmit="return checkForm(frmOne);" action="/cgi-bin/FormMail.pl">
<script>
function checkForm(form)
{
if(!form.agree.checked)
{
alert("You must agree to this disclaimer before applying.");
return false;
}
}
</script>
I hope that helped
Change <form action="/cgi-bin/FormMail.pl" method="POST" name="frmOne" id="frmOne"> to <form action="/cgi-bin/FormMail.pl" method="POST" name="frmOne" id="frmOne" onSubmit="validate_form();">
What other errors are you getting?
and change document.form1.cb.checked to document.frmOne.agree.checked
Give a try with document.getElementById("disclaimer").checked == false.

Categories

Resources