Validate a form by passing the form name as a constructor - javascript

I'm trying to validate a form by passing the form node through a constructor. I know using OO is a bit over the top but it's a request. I've got the code below, but when I try to alert out the values of the text boxes in function(form), they are coming up as undefined.
<SCRIPT LANGUAGE="JavaScript">
function Validator(fields) {
this.fields = fields;
}
Validator.prototype.validate = function (form) {
for (var i = 0, l = this.fields.length; i < l; i++) {
alert(this.fields[i].value);
if (this.fields[i].value == 0) {
alert("The field is empty");
return false;
}
}
}
var validator = new Validator(["username", "password"]);
function runValidate(form) {
validator.validate(form);
}
</SCRIPT>
</head>
<body>
<form NAME="AbbeyRoad">
<fieldset>
<legend>Please login</legend>
<div class="form-element">
<label for="username"><span class="shortkey">U</span>sername:</label>
<input type="text" name="username" id="username" accesskey="u">
</div>
<div class="form-element">
<label for="password"><span class="shortkey">P</span>assword:</label>
<input type="password" name="password" id="password" accesskey="p">
</div>
<input type="button" name="login" value="Login" id="login" onClick="runValidate(this.form)">
</fieldset>
</form>

Change:
alert(this.fields[i].value);
to:
alert(form[this.fields[i]].value);
and this:
if (this.fields[i].value == 0) {
to:
if (form[this.fields[i]].value == 0) {

Related

html form validation using javascript

i am trying to validate my html form using javascript. the validation works but it still submits.
ie. when clicking submit a text will appear saying "first name is required" but then still submits.
here is the javascript code:
function validateForm(form) {
formValid = true;
for(i = 0; i < form.length; i++) {
if(!requiredInput(form[i]))
formValid = false;
}
return formValid;
}
function requiredInput(element) {
if(!element.value.length) {
document.getElementById(element.id + 'Error').style.display = "inline-block";
return false;
} else {
document.getElementById(element.id + 'Error').style.display = "none";
return true;
}
return;
}
and here is the html code for the form:
<form action="http://tl28dfdsdsserv.westernsydney.edu.au/twainfo/echo.php" method="get" onsubmit="return validateForm(this);">
<h2>Validate you name:</h2>
<div>
<label for="fname">First Name</label>
<input type="text" id="fname" name="fname" placeholder="Given Name" onblur="requiredInput(this);">
<span class="error" id="fnameError">First Name is Required</span>
</div>
<div>
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lname" placeholder="Surname" onblur="requiredInput(this);">
<span class="error" id="lnameError">Last Name is Required</span>
</div>
<div>
<hr>
</div>
<div>
<input type="submit" value="Submit" name="submit" >
</div>
</form>
im not sure why it still submits.
EDIT: i need to debug this code and not change all of it
EDIT: i can not change the html code for this, i am to debug the javascript only
I think you need validate if its type submit :
function validateForm(form) {
formValid = true;
for(i = 0; i < form.length; i++) {
if(form[i].type != "submit"){
if(!requiredInput(form[i])){
formValid = false;
}
}
}
return formValid;
}
Your validation has the correct structure, however, if there is any JavaScript error, the "return false" will not cancel the form submission.
Go to your developer console and manually invoke the validateForm function. You can give the form an ID:
<form id="myform"...
Then, you can reference this in the console:
validateForm(document.getElementById('form'));
You will see a JavaScript error. Fix the error and your form will be intercepted.
<form action="http://tl28dfdsdsserv.westernsydney.edu.au/twainfo/echo.php" method="get"
onsubmit="return validateForm(event)">
<h2>Validate you name:</h2>
<div>
<label for="fname">First Name</label>
<input type="text" id="fname" name="fname" placeholder="Given Name" onblur="requiredInput(this);">
<span class="error" id="fnameError">First Name is Required</span>
</div>
<div>
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lname" placeholder="Surname" onblur="requiredInput(this);">
<span class="error" id="lnameError">Last Name is Required</span>
</div>
<div>
<hr>
</div>
<div>
<input type="submit" value="Submit" name="submit">
</div>
<script type="text/javascript">
function validateForm(e) {
form = e.target;
formValid = true;
for (i = 0; i < form.length; i++) {
if (!requiredInput(form[i]))
formValid = false;
}
return formValid;
}
function requiredInput(element) {
if (element.type == 'submit') {
return true;
}
if (element.value.length == 0) {
document.getElementById(element.id + 'Error').style.display = "inline-block";
return false;
} else {
document.getElementById(element.id + 'Error').style.display = "none";
return true;
}
}
this should work
Actually You can do it simple way, see below,
Modify your HTML
I remove onsubmit attribute and add form to ID
<form id="dsds" action="http://tl28dfdsdsserv.westernsydney.edu.au/twainfo/echo.php" method="get">
<h2>Validate you name:</h2>
<div>
<label for="fname">First Name</label>
<input type="text" id="fname" name="fname" placeholder="Given Name" onblur="requiredInput(this);">
<span class="error" id="fnameError">First Name is Required</span>
</div>
<div>
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lname" placeholder="Surname" onblur="requiredInput(this);">
<span class="error" id="lnameError">Last Name is Required</span>
</div>
<div>
<hr>
</div>
<div>
<input type="submit" value="Submit" name="submit" >
</div>
Remove your JS function and do like this,
$("#dsds").submit(function(e){
//call your functions here
return false; // return true if you want to submit the form
});
See the example,
JSFille
Use preventDefault() to disable the submit.
function validateForm(event, form) {
formValid = true;
for (i = 0; i < form.length; i++) {
if (!requiredInput(form[i])) {
formValid = false;
break;
}
}
if (!formValid) {
event.preventDefault();
}
return formValid;
}
And pass the event object in the onsubmit function like below.
<form action="http://tl28dfdsdsserv.westernsydney.edu.au/twainfo/echo.php" method="get" onsubmit="validateForm(event, this);">
function validateForm(form) {
formValid = true;
try {
for (i = 0; i < form.length; i++) {
if (!requiredInput(form[i]))
formValid = false;
}
} catch (error) {
console.error("validateForm=>", error)
}
return formValid;
}
function requiredInput(element) {
try {
const elementInputError = document.getElementById(element.id + 'Error');
if (!element.value.length) {
elementInputError && setDisplayError(elementInputError,"inline-block");
return false;
} else {
elementInputError && setDisplayError(elementInputError,"none");
return true;
}
} catch (error) {
console.error("requiredInput=>", error)
return false;
}
}
function setDisplayError(element,value) {
try {
element.style.display =value;
} catch (error) {
console.error("setDisplayError=>", error)
}
}
<form action="http://tl28dfdsdsserv.westernsydney.edu.au/twainfo/echo.php" method="get"
onsubmit="return validateForm(this);">
<h2>Validate you name:</h2>
<div>
<label for="fname">First Name</label>
<input type="text" id="fname" name="fname" placeholder="Given Name" onblur="requiredInput(this);">
<span class="error" id="fnameError">First Name is Required</span>
</div>
<div>
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lname" placeholder="Surname" onblur="requiredInput(this);">
<span class="error" id="lnameError">Last Name is Required</span>
</div>
<div>
<hr>
</div>
<div>
<input type="submit" value="Submit" name="submit">
</div>
</form>
The problem arose because it also validated the send button and because it did not have the termination of the failed id it could not find the item and an error occurred. Then when the error occurred it did not return anything the function and redirect you to the form action page.

Contact Form Redirecting Prevent Default Not Working

I've tried this many different ways... don't know why this is redirecting still. I suppose in the past I've always used a button instead of a submit input and as such I never ran into this issue. However, I think it's time to get to the bottom of this!
HTML FORM
<form class="col-xs-12" action="mail.php" method="POST" >
<h2 class="headerFont">Contact</h2>
<p>Use the form below to send to contact me via email. I will be in touch soon after receiving your message.</p>
<div class="row">
<div class="col-xs-12 col-sm-6">
<input class="col-xs-12" placeholder="Full Name" title="Enter Full Name" type="text" name="name">
<input class="col-xs-6" placeholder="Email Address" title="Enter Email Address" type="email" name="email">
<input class="col-xs-6" placeholder="Mobile Phone Number" title="Enter Mobile Phone Number" type="tel" name="phone">
<input class="col-xs-12" placeholder="Street Address" title="Enter Street Address" type="text" name="address">
<input type="text" name="_gotcha" id="_gotcha" style="display: none !important">
<select class="col-xs-12" name="service">
<option selected disabled>Select Service</option>
<option>Group Walking</option>
<option>Private Walking</option>
<option>Pet Sitting</option>
</select>
</div>
<div class="col-xs-12 col-sm-6">
<textarea class="col-xs-12" placeholder="Message Here" rows="10" name="message"></textarea>
</div>
</div>
<input type="submit" value="Send" onclick="formSubmit(e)">
</form>
JAVASCRIPT CODE
function formSubmit(e) {
e.preventDefault();
return false;
console.log("Ajax Init");
var form = e.target,
data = new FormData(),
xhr = new XMLHttpRequest();
for (var i = 0, ii = form.length - 1; i < ii; ++i) {
var input = form[i];
data.append(input.name, input.value);
if (input.getAttribute("name") !== "_gotcha") {
if (input.value === "" || input.value === null || input.value === "undefined") {
alert("Please fill out all form fields before submitting");
break;
}
}
}
xhr.open(form.method.toUpperCase(), form.action, true);
if (document.getElementById("_gotcha").value.length == 0){
xhr.send(data);
} else {
break;
}
xhr.onloadend = function () {
// done
for (var i = 0, ii = form.length - 1; i < ii; ++i) {
var input = form[i];
input.value = "";
}
alert("Message Sent - Thank You");
};
};
It seems a better option is to use onsubmit attribute.
function formSubmit(form) {
console.log("Ajax Init");
var data = new FormData(form), // simpler
xhr = new XMLHttpRequest();
for (var i = 0, ii = form.length - 1; i < ii; ++i) {
var input = form[i];
//data.append(input.name, input.value);
if (input.getAttribute("name") !== "_gotcha") {
if (input.value === "" || input.value === null || input.value === "undefined") {
alert("Please fill out all form fields before submitting");
// something went wrong, prevent form from submitting
return false;
}
}
}
xhr.open(form.method.toUpperCase(), form.action, true);
if (document.getElementById("_gotcha").value.length == 0) {
xhr.send(data);
} else {
// something went wrong, prevent form from submitting
return false;
}
xhr.onloadend = function() {
// done
for (var i = 0, ii = form.length - 1; i < ii; ++i) {
var input = form[i];
input.value = "";
}
alert("Message Sent - Thank You");
};
// everything went ok, submit form
return true;
};
<!-- note the use of return -->
<form class="col-xs-12" action="mail.php" method="POST" onsubmit="return formSubmit(this)">
<h2 class="headerFont">Contact</h2>
<p>Use the form below to send to contact me via email. I will be in touch soon after receiving your message.</p>
<div class="row">
<div class="col-xs-12 col-sm-6">
<input class="col-xs-12" placeholder="Full Name" title="Enter Full Name" type="text" name="name">
<input class="col-xs-6" placeholder="Email Address" title="Enter Email Address" type="email" name="email">
<input class="col-xs-6" placeholder="Mobile Phone Number" title="Enter Mobile Phone Number" type="tel" name="phone">
<input class="col-xs-12" placeholder="Street Address" title="Enter Street Address" type="text" name="address">
<input type="text" name="_gotcha" id="_gotcha" style="display: none !important">
<select class="col-xs-12" name="service">
<option selected disabled>Select Service</option>
<option>Group Walking</option>
<option>Private Walking</option>
<option>Pet Sitting</option>
</select>
</div>
<div class="col-xs-12 col-sm-6">
<textarea class="col-xs-12" placeholder="Message Here" rows="10" name="message"></textarea>
</div>
</div>
<!-- upon clicking on the submit button, it will trigger the form's onsubmit handler -->
<input type="submit" value="Send">
</form>
i suggest to use jquery inside of core javascript becuase in javascript it to mush code want to write , i write for you in jquery
step 1: : give id to form tag id="myForm"
step 2: : write script like this
<script>
$('#myForm').submit(function(e){
e.preventDefualt();
data = $(this)..serialize();
});
</script>

form validation problems with jquery / javascript

This is my first real project which involves form validation. I am experiancing a problem which I can not find the solution to.
The objective is this, there is a continue button which will be activated once all the field inputs have been passed as valid. I am going about this by creating seperate variables, all initially set as false, devoted to checking each input field. When the user has entered correct validation data, the variable is set to true.
I then run an if statement to check if all the variables are set to true, and if so, I activate the continue button which, when clicked, slides the next part of the form into the page.
HTML:
<div class="container">
<h3>Step 3: Your Details</h3>
<!-- SLIDE-IN DIV TO REPRESENT DAY PASS -->
<div class="row chosenmembership">
<div class="col-md-12 text-center" id="yourdetails">
<form action="" method="">
<div class="form-group">
<label for="email">Email:</label>
<input type="text" placeholder="Email Address" id="email" class="form-control your-details">
<span class="warning" id="email-warning"></span>
</div>
<div class="form-group">
<label for="name">Name:</label>
<input type="text" placeholder="Full Name" id="name" class="form-control your-details">
<span class="warning" id="name-warning"></span>
</div>
<div class="form-group">
<label for="number">Contact Number:</label>
<input type="text" placeholder="Contact Number" id="number" class="form-control your-details">
<span class="warning" id="number-warning"></span>
</div>
<div class="form-group">
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" class="form-control your-details">
<span class="warning" id="dob-warning"></span>
</div>
</form>
<input type="submit" id="submit" value="CONTINUE">
</div>
</div>
</div>
JAVASCRIPT / JQUERY:
//collection of input form fields//
var formSubmit = $("#submit");
var emailField = $("#email");
var nameField = $("#name");
var numberField = $("#number");
//Switch to true when each validation has passed//
emailValidated = false;
nameValidated = false;
numberValidated = false;
//email validation check//
emailField.on("input",function(){
var emailInput = $(this).val()
var testExp = new RegExp(/[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$/);
if (emailInput < 1) {
$("#email-warning").html("Email is required!");
$("#email-warning").css("visibility","visible");
emailValidated = false;
}
else if (!testExp.test(emailInput)){
$("#email-warning").html("Please enter a valid email");
$("#email-warning").css("visibility","visible");
emailValidated = false;
} else {
$("#email-warning").css("visibility","hidden");
emailValidated = true;
}
})
//name validation check//
nameField.on("input",function(){
var nameInput = $(this).val()
if (nameInput < 1) {
$("#name-warning").html("Name is required");
$("#name-warning").css("visibility","visible");
nameValidated = false;
} else {
$("#name-warning").css("visibility","hidden");
nameValidated = true;
}
})
//contact number validation check//
numberField.on("input",function(){
var numberInput = $(this).val()
if (typeof numberInput !== "number" && numberInput.length < 9) {
$("#number-warning").html("Please enter a valid number");
$("#number-warning").css("visibility","visible");
numberValidated = false;
} else {
$("#number-warning").css("visibility","hidden");
numberValidated = true;
}
})
if (emailValidated && nameValidated && numberValidated){
alert("correct");
}
})
at the moment, I am simply using the alert prompt to test if it is working, but it fails.
As mentioned, this is my first real form validation. Any other tips or advice would be greatly appreciated. Thanks for the help in advance.
There were a couple things that I found from copying pasting your snippets of code. 1 there was an ending "})" without a beginning $(document).ready(function(){ ". 2 none of your ".on" statements had an ending semi colon.
Here is my javascript with a small change
$(document).ready(function () {
//collection of input form fields//
var formSubmit = $("#submit");
var emailField = $("#email");
var nameField = $("#name");
var numberField = $("#number");
//Switch to true when each validation has passed//
emailValidated = false;
nameValidated = false;
numberValidated = false;
//email validation check//
emailField.on("input", function () {
var emailInput = $(this).val()
var testExp = new RegExp(/[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$/);
if (emailInput < 1) {
$("#email-warning").html("Email is required!");
$("#email-warning").css("visibility", "visible");
emailValidated = false;
}
else if (!testExp.test(emailInput)) {
$("#email-warning").html("Please enter a valid email");
$("#email-warning").css("visibility", "visible");
emailValidated = false;
} else {
$("#email-warning").css("visibility", "hidden");
emailValidated = true;
enableContinue();
}
});
//name validation check//
nameField.on("input", function () {
var nameInput = $(this).val()
if (nameInput < 1) {
$("#name-warning").html("Name is required");
$("#name-warning").css("visibility", "visible");
nameValidated = false;
} else {
$("#name-warning").css("visibility", "hidden");
nameValidated = true;
enableContinue();
}
});
//contact number validation check//
numberField.on("input", function () {
var numberInput = $(this).val()
if (typeof numberInput !== "number" && numberInput.length < 9) {
$("#number-warning").html("Please enter a valid number");
$("#number-warning").css("visibility", "visible");
numberValidated = false;
} else {
$("#number-warning").css("visibility", "hidden");
numberValidated = true;
enableContinue();
}
});
enableContinue = function () {
if (emailValidated && nameValidated && numberValidated) {
$('#submit').prop('disabled', false);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<h3>Step 3: Your Details</h3>
<!-- SLIDE-IN DIV TO REPRESENT DAY PASS -->
<div class="row chosenmembership">
<div class="col-md-12 text-center" id="yourdetails">
<form action="" method="">
<div class="form-group">
<label for="email">Email:</label>
<input type="text" placeholder="Email Address" id="email" class="form-control your-details">
<span class="warning" id="email-warning"></span>
</div>
<div class="form-group">
<label for="name">Name:</label>
<input type="text" placeholder="Full Name" id="name" class="form-control your-details">
<span class="warning" id="name-warning"></span>
</div>
<div class="form-group">
<label for="number">Contact Number:</label>
<input type="text" placeholder="Contact Number" id="number" class="form-control your-details">
<span class="warning" id="number-warning"></span>
</div>
<div class="form-group">
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" class="form-control your-details">
<span class="warning" id="dob-warning"></span>
</div>
</form>
<input type="submit" class="btn btn-primary" id="submit" disabled="disabled" value="CONTINUE">
</div>
</div>
</div>
Your form CONTINUE button becomes enables once all fields have a value. Note: I did not try to improve your javascript any, just made it work.
Right now you synchronically check validation variables at script, so they are all false. You have to asynchronically check them after form submit. Just add event listener to form submit to check variables like this:
document.getElementById('#form').addEventListener('submit', function(){
if (emailValidated && nameValidated && numberValidated){
alert("correct");
}
});
Don't forget to set id to your form.
You may be able to save a lot of work if you leverage some of the built in HTML5 form validation. https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation
This simple example adds a new field every time you submit the form, as long as the existing fields are valid. You would need to test the state of the form to see if you should be adding another section or submitting.
$('form').on('submit', function() {
$(this).find('fieldset').append('<input type="text" required />');
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset>
<input type="text" required />
</fieldset>
<input type="submit" id="submit" value="continue" />
</form>

Email validation for specific domain name with form action changer

<form name="form" method="post" action="">
<input name="email" type="email" id="email" placeholder="email#school.com" required>
<input name="name" type="text" id="name" placeholder="name" required>
<button type="submit" id="submit">Submit!</button>
</form>
<script>
function IsValidEmail(email)
$(document).ready(function() {
$("#form").submit(function() {
var allowedDomains = [ 'school1.com', 'school2.com', 'school3.com' ];
if ($.inArray(str[0], allowedDomains) !== -1) {
//acceptable
}else{
//not acceptable
}
document.getElementById('email').onchange = function(){
document.getElementById('FORM_ID').action = '/'+this.value;
}
</script>
can u help me please
thank you
please check this code,
<form name="form" id="form_action" method="post" action="">
<input name="email" type="email" id="email" placeholder="email#school.com" required>
<input name="name" type="text" id="name" placeholder="name" required>
<button type="submit" id="submit" onclick="check_email()">Submit!</button>
</form>
and this is your javascript code
<script type="text/javascript">
function check_email(){
var email = document.getElementById("email").value;
if(email == ''){
alert('Enter email');
return false;
}
if(email.indexOf('school1.com') !== -1)
{
document.getElementById("form_action").action ="school1.com";
document.getElementById('form_action').submit();
} else {
document.getElementById("form_action").action ="school2.com";
document.getElementById('form_action').submit();
}
}
</script>
you want to answer using javascript so this is javascipt answer
The first problem is that you have no form ID, so your document.getElementByID has nothing to target. Let's first give it an id emailform:
<form id="emailform" name="form" method="post" action="">
Then you need to run the validity check on change:
document.getElementById('email').onchange = function() {
var allowedDomains = ['school1.com', 'school2.com', 'school3.com'];
if ($.inArray(this.value, allowedDomains) !== -1) {
//acceptable
}
}
Then you can simply update the form with jQuery, setting the action attribute:
document.getElementById('email').onchange = function() {
var allowedDomains = ['school1.com', 'school2.com', 'school3.com'];
if ($.inArray(this.value, allowedDomains) !== -1) {
var action = '/'+this.value;
$("#emailform").attr("action", action);
}
}
Hope this helps! :)

How to submit a form from script

I have a simple form:
<form id="form" method="post" action="email.php">
<input id="name" name="name" type="text" placeholder="Name" />
<input name="email" id="email" type="text" placeholder="Email" />
<textarea name="text" id="msg" placeholder="Comment"></textarea>
<input type="button" value="SUBMIT" id="submit" onclick="empty()"/>
</form>
and an empty() function for checking if all inputs are there:
function empty(){
var x; var y; var z;
x = document.getElementById("name").value;
y = document.getElementById("email").value;
z = document.getElementById("msg").value;
if (x == "" || y == "" || z == "") {
document.getElementById("errors").innerHTML = "All inputs must be present before submitting.";
return false;
}else{
document.form.submit(); /*this doesn't work*/
}
}
But I can't seem to get the form to submit...
The problem is with the button type. Try this:
<script>
function empty() {
var x;
var y;
var z;
x = document.getElementById("name").value;
y = document.getElementById("email").value;
z = document.getElementById("msg").value;
if (x == "" || y == "" || z == "") {
document.getElementById("errors").innerHTML = "All inputs must be present before submitting.";
return false; // the only reason this worked previously is that the input type was wrong so the form didn't submit
} else {
return true; // return true instead of trying to submit the form with js
}
}
</script>
<form id="form" method="post" action="email.php">
<input id="name" name="name" type="text" placeholder="Name" />
<input name="email" id="email" type="text" placeholder="Email" />
<textarea name="text" id="msg" placeholder="Comment"></textarea>
<input type="submit" value="SUBMIT" id="submit" onclick="return empty();" />
<!-- change the button type to submit and return the value from the empty function (false will prevent the default action of the button - stop the form submitting, true will allow the form to submit) -->
</form>
<div id="errors"></div>
Noticed this doesn't work as a snippet so this is it working in a fiddle
You need to define name of the form.After define this form can be submit using javascript.
To check example you can follow this example-
<form name="myform" action="handle-data.php">
Search: <input type='text' name='query' />
Search
</form>
<script type="text/javascript">
function submitform()
{
document.myform.submit();
}
</script>

Categories

Resources