Uncaught ReferenceError: form is not defined - javascript

Can't for the life of me figure this out. any help would be greatly appreciated!
This is the message I receive in Google Chrome when I test the script:
Navigated to http://localhost/contact.php
form2.js:2 Uncaught ReferenceError: form is not definedform2.js:2 validatecontact.php:24 onsubmit
Navigated to http://localhost/contact.php
My contact.php file:
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript" src="form2.js"></script>
<?php require 'Includes/Header.php'; ?>
<div class="wrapper">
<div id="contact-form">
<h5>Contact Form</h5>
<form name="contact" form method="post" action="contact.php"
onsubmit="return validate(contact)">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<label for="email">Email:</label>
<input type="email" id="email" name="email">
<label for="message">Message:</label>
<textarea id="message" name="message"></textarea>
<button type="submit">Submit</button>
</form>
<div class="clear"></div>
</div>
</div>
<?php require 'Includes/Footer.php'; ?>
My form2.js file:
function validate(contact){
var name = form.name.value;
var email = form.email.value;
var message = form.message.value;
if (name.length == 0 || name.length > 200)
{alert ("You must enter a name.");
return false;
}
if (email.length == 0 || email.length > 200)
{alert ("You must enter a email.");
return false;
}
if (message.length == 0)
{alert ("You must enter a message.");
return false;
}
return true;
}

form is a javascript object. That object does not exist within this file, which is why the error is being thrown. If you want to validate this form, you need to get a reference to it from the DOM first, using document.contact.
function validate(contact){
var form = document.contact,
name = form.name.value,
email = form.email.value,
message = form.message.value;
if (name.length == 0 || name.length > 200) {
alert ("You must enter a name.");
return false;
}
if (email.length == 0 || email.length > 200) {
alert ("You must enter a email.");
return false;
}
if (message.length == 0) {
alert ("You must enter a message.");
return false;
}
return true;
}

try using jquery by adding
<script type="text/javascript" charset="utf-8" src="./jquery-1.9.1.js" />
to the header (you will have to download it or then add:
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
to get the latest)
then in your function get the values of the input fieds as follow:
var name = $('#name').value;
var email = $('#email').value;
var message = $('#message').value;

Access forms like this
<form action="#" name="test_form">
<input name="firstname" value="hello world"/>
</form>
var valueOfInput = document.test_form.firstname.value
you can also go like documents.forms["test_form"].elements
so maybe passing in document.contact can help ...
otherwise look at libraries like jQuery which give you a nice api to access DOM elements.

The error is what it says. You don't have a form variable defined (From what you've shared).
Also, it looks like you're trying to validate your form by accessing the values of the input fields. Here is how you should / could do it -
function validate(contact){
var name = document.getElementsByName('name')[0].value;
// You can also do the following
// var name = document.getElementById('name').value;
// var name = document.forms['contact'].elements['name'].value;
var email = document.getElementsByName('email')[0].value;
var message = document.getElementsByName('message')[0].value;
if (name.length == 0 || name.length > 200)
{
alert ("You must enter a name.");
return false;
}
if (email.length == 0 || email.length > 200)
{
alert ("You must enter a email.");
return false;
}
if (message.length == 0)
{
alert ("You must enter a message.");
return false;
}
return true;
}

Related

JavaScript Validation error message is not disappearing after I click submit

The code below validates a form with two fields. When I click the submit button without any data the error messages would show which is working fine but if I input data after and click submit button the error message doesn't disappear.
<script>
function validateForm() {
var valid = true;
var x = document.forms["myForm"]["activityName"].value;
if (x == "" || x == null) {
document.getElementById("activityName").innerHTML = "Please Enter Activity Name";
valid= false;
}
var r = document.forms["myForm"]["reporter"].value;
if (r == "") {
document.getElementById("reporter").innerHTML = "Please Enter Reporter";
valid = false;
}
return valid;
}
</script>
</head>
<body>
<form action="#" method="post" name="myForm" onsubmit=" return validateForm()">
<div>
<label for="myActivityName">*Activity Name:</label>
<input type="text" name="activityName" value="" placeholder="Enter Activity Name" />
<p id="activityName"></p>
</div><br>
<div>
<label for="reporter">*Reporter:</label>
<input type="text" name="reporter" value="" placeholder="Enter Reporter " />
<p id="reporter"></p>
</div><br>
<input type="submit" value="Submit" >
</form>
</body>
The other answer is right, but here is some code to back it up with. Notice that the innerHTML of both activityName and reporter get (re)set back to empty before the validation occurs:
function validateForm() {
var valid = true;
document.getElementById("activityName").innerHTML = "";
document.getElementById("reporter").innerHTML = "";
var x = document.forms["myForm"]["activityName"].value;
if (x == "" || x == null) {
document.getElementById("activityName").innerHTML = "Please Enter Activity Name";
valid= false;
}
var r = document.forms["myForm"]["reporter"].value;
if (r == "") {
document.getElementById("reporter").innerHTML = "Please Enter Reporter";
valid = false;
}
return valid;
}
Your problem is you never "unvalidate" the form a.k.a. remove the previous validation errors. Before you return from validation, if there were no errors, just revert your validation checks. This will ensure it will "clean" your interface if nothing is wrong.

Javascript skipping the if and if else conditions and directly jumping to else condition

I am new to JavaScript and just trying my hands on to JavaScript with a simple login page.
I have created a login page using HTML and CSS and JavaScript for validations. But my JavaScript code is not working properly.
It is skipping the if conditions and directly jumping to else part and sometimes it is just validating the first if else part for username validation.
Below is my JavaScript and html code.
I am using and external JavaScript.
function ValidateSignIn() {
//Variable declarations and initialization
var username = document.getElementsByName("username").value;
var password = document.getElementsByName("password").value;
//Validation of username and password fields
if (username == "Temp" && password == "123") {
alert("Login Successful!!");
window.location = "C:\Users\metyagi\Downloads\Personal data\THE SCM QUIZ\WelcomePage.html";
} else if (username == null || username == "") {
alert("Please enter CEC ID");
} else if (password == null || password == "") {
alert("Please enter Password");
} else {
alert("Username or Password is incorrect, Please try again!!");
}
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>The SCM Quiz Login Page</title>
<link rel="stylesheet" type="text/css" href="css\SignIn.css" />
<script type="text/javascript" src="C:\Users\mt\Downloads\data\test\SignIn.js"></script>
</head>
<body>
<!--Div for Logo-->
<Div class="logo">
<img src="images\logo.png" />
</Div>
<!--Div for form-->
<Div class="loginform">
<h3>Login </h3>
<h6>Required fields are marked with *</h6>
<form method="post" action="" name="SignIn">
<INPUT TYPE="text" name="username" placeholder="Please Enter Username*">
</br>
</br>
<INPUT TYPE="password" name="password" placeholder="Please Enter Password*">
</br>
</br>
<INPUT TYPE="submit" name="SignIn" value="SIGN IN" onclick="ValidateSignIn()">
Forgot Password?
<p class="message">Not Registered Yet? Sign Up!
</P>
</form>
</Div>
</body>
</html>
try this :
var username = document.getElementsByName("username")[0].value;
var password = document.getElementsByName("password")[0].value;
or set id on your elements and try :
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
You are using document.getElementsByName("username") method ,From the name (getElementsByName) of the method itself you come to know that it returns the nodelist collection with name as username. so you need to give correct index number to get the value. otherwise you can also use the getElementById() method by defining id for text field in Html.
function ValidateSignIn() {
//Variable declarations and initialization
var username = document.getElementsByName("username")[0].value;
var password = document.getElementsByName("password")[0].value;
//Validation of username and password fields
if (username == "Temp" && password == "123") {
alert("Login Successful!!");
window.location = "C:\Users\metyagi\Downloads\Personal data\THE SCM QUIZ\WelcomePage.html";
} else if (username == null || username == "") {
alert("Please enter CEC ID");
} else if (password == null || password == "") {
alert("Please enter Password");
} else {
alert("Username or Password is incorrect, Please try again!!");
}
}
<html>
<head>
<meta charset="utf-8">
<title>The SCM Quiz Login Page</title>
<link rel="stylesheet" type="text/css" href="css\SignIn.css" />
<script type="text/javascript" src="C:\Users\mt\Downloads\data\test\SignIn.js"></script>
</head>
<body>
<!--Div for Logo-->
<Div class="logo">
<img src="images\logo.png" />
</Div>
<!--Div for form-->
<Div class="loginform">
<h3>Login </h3>
<h6>Required fields are marked with *</h6>
<form method="post" action="" name="SignIn">
<INPUT TYPE="text" name="username" placeholder="Please Enter Username*">
</br>
</br>
<INPUT TYPE="password" name="password" placeholder="Please Enter Password*">
</br>
</br>
<INPUT TYPE="submit" name="SignIn" value="SIGN IN" onclick="ValidateSignIn()">
Forgot Password?
<p class="message">Not Registered Yet? Sign Up!
</P>
</form>
</Div>
</body>
</html>
Basically you want to add some validation for your username and password. What you have written in the first if statement is to validate if both are valid and that should be working correctly.
else if(username == null || username == ""){
alert("Please enter CEC ID");
}
This will stop further evaluation if username is not valid. In case you want to check if password too is not valid, you will need to write in a different if /else block and not in continuation of the username validation.
You should separate validating user input and checking user credentials to make the code clear and easy to read, please refer the code below:
function ValidateSignIn(){
var hasError = false;
//Variable declarations and initialization
var username = document.getElementsByName("username")[0].value;
var password = document.getElementsByName("password")[0].value;
//Validation of username and password fields
if (!username) { // this will check null, undefined, and empty string
hasError = true;
alert("Please enter CEC ID");
} else if (!password) {
hasError = true;
alert("Please enter Password");
}
if (!hasError) {
if(username == "Temp" && password == "123"){
alert("Login Successful!!");
window.location = "C:\Users\metyagi\Downloads\Personal data\THE SCM QUIZ\WelcomePage.html";
} else {
alert("Username or Password is incorrect, Please try again!!");
}
}
}
You are using document.getElementsByName and according to your code you will get undefined in username and password. So you need to do this:
function ValidateSignIn()
{
//Variable declarations and initialization
var username = document.getElementsByName("username")[0].value;
var password = document.getElementsByName("password")[0].value;
//Validation of username and password fields
if(username == "Temp" && password == "123")
{
alert("Login Successful!!");
window.location = "C:\Users\metyagi\Downloads\Personal data\THE SCM QUIZ\WelcomePage.html";
}
else if(username == null || username == "")
{
alert("Please enter CEC ID");
}
else if (password == null || password == "")
{
alert("Please enter Password");
}
else
{
alert("Username or Password is incorrect, Please try again!!");
}
}
UPDATE1:
If you want to prevent fields not to clear on submit you can do use preventDefault method of the event object like this:
$("#Formid").submit(function(event){
event.preventDefault()
})
OR
$("#Formid").submit(function(event){
e.returnValue = false;
})

form is submitting instead return false javascript

I am trying to test my form for validation. I don't have an .asp or .php file so I was informed I could use action="". My code doesn't seem to function right.On codepen it shows as values being posted. Jsfiddle gives me an error thats a paragraph long. In browser the page just seems to refresh. I have no alerts showing for anything....
what am I doing wrong here?
HTML:
<form name="name_form" action="" onsubmit="ValidateFormJS()" method="post">
First Name:
<input type="text" name="first_name">
<br> Last Name:
<input type="text" name="last_name">
<br>
<input type="submit" value="Submit">
</form>
Javascript:
function ValidateFormJS() {
var first = document.forms["name_form"]["first_name"].value;
var last = document.form["name_form"]["last_name"].value;
if (first == null || first == "") {
alert("First name must be filled out.");
return false;
} else if (last == null || last == "") {
alert("Last name must be filled out.");
return false;
} else {
alert("Form Submitted.");
return true;
}
}
The returned values from the function are never used.
You forgot return before the function call on onsubmit event.
onsubmit="return ValidateFormJS()"
Another problem is that you're using document.form to get the value of last name. It should be document.forms.
The last else can be removed.
Demo
var form = document.forms["name_form"];
function ValidateFormJS() {
var first = form["first_name"].value,
last = form["last_name"].value;
if (first == null || first == "") {
alert("First name must be filled out.");
return false;
} else if (last == null || last == "") {
alert("Last name must be filled out.");
return false;
}
}
<form name="name_form" action="" onsubmit="return ValidateFormJS()" method="post">
First Name:
<input type="text" name="first_name">
<br>Last Name:
<input type="text" name="last_name">
<br>
<input type="submit" value="Submit">
</form>
try this
in view
<form name="name_form" action="" onsubmit="return ValidateFormJS();" method="post">
in js code
function ValidateFormJS() {
var first = document.forms["name_form"]["first_name"].value;
var last = document.form["name_form"]["last_name"].value;
if (first == null || first == "") {
alert("First name must be filled out.");
return false;
} else if (last == null || last == "") {
alert("Last name must be filled out.");
return false;
}
alert("Form Submitted.");
return true;
}

Getting JavaScript validation to work with PHP

<?php
if (isset($_POST['submit']) ) {
//send to database
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function validateForm() {
var usernameentry = document.forms["registrationform"]["username2"].value;
var passwordentry = document.forms["registrationform"]["password2"].value;
var nameentry = document.forms["registrationform"]["password2"].value;
var emailentry = document.forms["registrationform"]["email"].value;
var atpos = emailentry.indexOf("#");
var dotpos = emailentry.lastIndexOf(".");
if (usernameentry.length < 3 || username.length > 20){
alert("Username must be inbetween 4 and 20 characters");
return false;
}
else if (passwordentry.length < 3 || password.length > 20){
alert("Password must be inbetween 4 and 20 characters");
return false;
}
else if (nameentry.length < 3 || name.length > 45){
alert("Name must be inbetween 4 and 45 characters");
return false;
}
else if (atpos<1 || dotpos<atpos+2 || dotpos+2>=emailentry.length || emailentry.length > 154) {
alert("Not a valid e-mail address");
return false;
}
else
{
return true;
}
}
</script>
</head>
<body>
<form name="registrationform" method="post" action="login.php" onsubmit="return validateForm();">
Name: <input type="text" name="name"/>
<br/>
<br/>
Email: <input type="text" name="email"/>
<br/>
<br/>
Username: <input type="text" name="username2"/>
<br/>
<br/>
Password: <input type="password" name="password2"/>
<br/>
<br/>
<input type = "submit" name = "submit" value = "submit" />
<br/>
<br/>
</form>
</body>
I want the contents of the if statement to run ONLY when the form has been validated with JavaScript, it runs regardless of whether the value returns is true or false.
I'm guessing what I need to do is similar to
if (isset($_POST['submit']) && onsubmit == true)
Obviously that's not right, but I don't know how to do it.
I know validating with php is a much more logical approach, but I need to demonstrate use of JavaScript.
You don't need to do that. When the form is validated, it will be sent to login.php
You can see this question HTML/Javascript: Simple form validation on submit
Also, there are a lot of libraries which could help you
http://www.javascript-coder.com/html-form/javascript-form-validation.phtml

Validating a form in Javascript not working

I'm trying to validate a form using JavaScript, but the code doesn't seem to execute. The Form is being processed using php which is working just fine. But, the validation is not working. Can someone please help me with this.
<script>
function validateForm(){
var x = document.getElementById('name');
var email = document.getElementById('email');
var num = document.getElementById('number');
var size = document.getElementById('size');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var atpos=email.value.indexOf("#");
var dotpos=email.value.lastIndexOf(".");
if (x.value == null || x.value == "") {
alert("Please Enter your name");
x.foucs;
x.style.background = 'Yellow';
return false;
}
if(!filter.test(email.value){
alert('Please provide a valid email address');
email.focus;
email.value="";
return false;
}
if(num.value == null && num.value == ""){
alert('Please enter your mobile number');
num.focus();
}
if(!isNan(num.value){
alert('Please enter a valid number');
num.focus();
num.style.background();
return false;
}
return false;
}
</script>
And here is my html code.
<form method="post" name="myForm " onsubmit="return validateForm()" action="myprocessingscript.php" >
<input type="text" name="name" placeholder="Name" class="text" id="name" />
<input name="email" placeholder="Email" type="text" class="text" id="email"/>
<input name="number" placeholder="Mobile Number" type="text" class="text" id="number"/>
<input name="size" placeholder="Size" type="text" class="text" id="size" />
<input type="Submit" value="Submit" class="button">
Working fiddle
Correct the spelling of foucs and ensure all references have parenthesis such as:
email.focus();
Without parenthesis, the function is not called. It's valid Javascript but it won't do anything.
You also missed a closing ) here:
if(!filter.test(email.value){
// ^ add another )
and here:
if(!isNan(num.value){
// ^ add another )
!isNan(....) should be isNaN(....). Javascript is case sensitive and you shouldn't be "notting" it here. isNaN is saying "is not a number" so it's already "notted".
On the line below, style has no background function. Looks like you want to assign a value here not call a function:
num.style.background(); // change to assign value.
On this line, change && to ||:
if(num.value == null && num.value == ""){
// ^ should be ||
Finally, remove the return false at the end.
Try using x.focus();
x.foucs; is not a valid statement, and neither is email.focus;.
These aren't right I don't think:
email.focus;
// Try email.focus();
and
x.foucs;
// Try x.focus();
Also looking at your code I don't see a </form>
Try this:
function validateForm(){
var x = document.getElementById('name');
var email = document.getElementById('email');
var num = document.getElementById('number');
var size = document.getElementById('size');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var atpos = email.value.indexOf("#");
var dotpos = email.value.lastIndexOf(".");
if (x.value == null || x.value == "") {
alert("Please Enter your name");
x.focus();
x.style.background = 'Yellow';
return false;
}
if(!filter.test(email.value){
alert('Please provide a valid email address');
email.focus();
email.value="";
return false;
}
if(num.value == null || num.value == ""){
alert('Please enter your mobile number');
num.focus();
return false;
}
if(!isNaN(num.value)){
alert('Please enter a valid number');
num.focus();
num.style.background = "Yellow";
return false;
}
return true;
}

Categories

Resources