JavaScript Login Form Not Validating - javascript

Good Evening,
I am trying to create a simple JavaScript login form that will validate by checking only 1 specific email address which has been declared and 1 password that has been declared.
However, no matter what is typed into the fields, even if nothing is present, once the submit button is clicked, the user is directed to the desired page.
I need it to only allow the desired page if the email address and password are the correct. Otherwise, notify them that it is incorrect.
Here is a link to [codepen][1] so you can see the page and script.
https://codepen.io/m0rrisim0/pen/bmzyqj
Any help is appreciated in figuring out why the script is not validating.

You have to use the attribute value from document.getElementById method,
like the following example: document.getElementById("UserName").value
function validate() {
'use strict';
var UserName = document.getElementById('UserName').value;
var email = "adrian#tissue.com";
var Password = document.getElementById('Password').value;
var pass = "welcome1";
if ((UserName == email) && (Password == pass)) {
return true;
} else {
alert("UserName and/or Password Do Not Match");
return false;
}
}
Your form's inputs lack the id atrribute and should return the function on submit event.
<form action="Issues.html" method="post" id="loginform" onsubmit="return validate()">
UserName:
<input type="text" name="UserName" id="UserName">
<br>
<br>
Password:
<input type="password" name="Password" id="Password">
<hr>
<input type="submit" value="Submit">
</form>

Your problem was getElementById(), this function requires a argument and cause a error. Because of this error the line loginform.onsubmit = validate; was never reached so the submit button submit the form without calling a validate function.
There is no need to put this line inside the if statement, but if you want you can change a little bit to getElementById without the parentesis, this way it evaluates to a function that in js is truthy.
You can check a working version of you code here:
if (document && document.getElementById) {
var loginform = document.getElementById('loginform');
loginform.onsubmit = validate;
}
https://codepen.io/francispires/pen/mzvYKX
You can improve this validation

Related

Javascript email validation failing on a valid email address?

I seem to be unable to get a basic javascript email validation function to work correctly. It keeps returning that the email address is invalid even when using a real email address.
Could someone please point me in the right direction as i couldn't find the problem on any other similar SO posts. I don't think it's the function itself, but perhaps how i am calling it? I have posted the code below.
// E-mail validation via regular expression - taken from SO solution
// Needs to be accessible for other Forms to use
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
// Validate Contact Form
function validate_contact(evt) {
var error = '';
// Set Veriables
var email = document.getElementById("contact_email");
// Validate Other Fields Here
// - Removed for Example -
// Validate Email Address
if (!isValidEmailAddress(email)) {
error += '- Please enter a valid Email Address.\n';
}
// Show Error Notice
if (error != '') {
error = 'The form has not been completed correctly, please check the following:\n\n' + error;
alert(error);
evt.preventDefault(); // Stop the event
} else {
// Proceed
}
}
// Get reference DOM elements
var contact_form = document.getElementById("contact_form");
// Set up event - Contact Form Validation
contact_form.addEventListener("submit", validate_contact);
// Set up event - Other Form Validation
//other_form.addEventListener("submit", validate_other);
<form id="contact_form" method="post" action="" autocomplete="off">
<input type="text" id="contact_email" name="email" value="">
<input type="submit" id="submit">
</form>
You should do some basic debugging. Look at the contents of the variables you are testing.
var email = document.getElementById("contact_email");
The value of email is the input element, not the text entered into it. For that you need to read its .value property.
Solution is to add ".value"
var email = document.getElementById("contact_email").value;

Why isnt my javascript function being run?

I'm trying to create a log-in page that validates data before it gets submitted to my php page that handles it. I'm using javascript to validate. This is my code:
<div class = mainInfo>
<?php include "header.php"; ?>
<form name = SignUpForm action = signUpHandler.php method ='POST' class = inputLists>
username: <input type = text name = "userName">
password: <input id= "p1" type = password name = "password">
reenter password: <input id ="p2" type = password name = "passwordConfirmation">
<input type="submit" name =" submitButton" value ="submit">
</form>
<div id="feedback">
</div>
</div>
<script>
function validate()
{
document.getElementById("feedback").innerHTML = "functionbeingcalled";
var p1 = document.getElementById("p1").value,
p2 = document.getElementById("p2").value);
if( ! p1===p2 )
{
document.getElementById("feedback").innerHTML = "passwords dont match";
}
if(p1==="")
{
document.getElementById("feedback").innerHTML = "Must have a password";
}
}
window.setInterval(validate(),1000);
</script>
<?php include "footer.php"; ?>
I would've thought that this script should run every second from the time that the page loads, but the script isn't being run at all. This line:
document.getElementById("feedback").innerHTML = "functionbeingcalled";
isn't working either.
Besides for this question, is it possible to validate data before submitting using only php? I'm new to web programming.
Pass the function instead of calling it.
// no parentheses!
window.setInterval(validate, 1000);
And this is wrong.
if( ! p1===p2 )
it should be this
if( p1!==p2 )
because of the higher precedence of the prefix !
I would suggest that you add listeners on your input fields! ;)
It will then only run the validation code when changes are made. In other words; only when necessary.
It will run the validation code "immediately" when input is changes. Instead of validation every 1000 ms.
I see you are not using jQuery (yet)? If you want to validate on 'change' using plain js, here is a solution: Plain js solution
If you are okay with adding the jQuery library to you code, then it can be done very easy like this jQuery solution
Well, you've got several issues...
First, with setInterval(), you only pass a reference to the function that should be called (validate in your case), you don't actually invoke it as you are doing (validate()). This essentially runs validate immediately and then sets the return value from it as the function to be called every second. Since validate() doesn't return a value, nothing happens every second thereafter.
You also have a typo with: if( ! p1===p2 ), which indicates that the Boolean opposite of p1 is being tested against p2. What you want is: if(p1 !== p2 ), which is how you express "not strictly equal to".
Now, really you are going about validation the wrong way. Instead of running a validation function on a timer, which is inefficient, you'd want to validate in one or more of these cases:
just before the entire form is submitted
just after the user leaves a form field
as the user is entering data
some combination of all 3
Each of those scenarios is handled through event handlers and a working example of each is shown below.
// Get the DOM references you'll need just once:
var feedback = document.getElementById("feedback");
// Don't set variables equal to property values of DOM elements because
// if you decide you need a different property value, you have to re-scan
// the DOM for the same element all over again.
var p1 = document.getElementById("p1")
var p2 = document.getElementById("p2");
var form = document.querySelector("form");
// Use this to validate when submit is pressed (causing form to be submitted):
form.addEventListener("submit", function(evt){
// If validate function returns false, don't submit
if(!validate()){
evt.preventDefault(); // cancel the form submission
feedback.textContent = "Can't submit. Form is not valid!";
}
});
// Get the elements that need to be validated:
var inputs = document.querySelectorAll("input[type=text],input[type=password]");
// Convert that node list into an array:
inputs = Array.prototype.slice.call(inputs);
// Loop over array and set up event handlers for inputs
inputs.forEach(function(input){
input.addEventListener("blur", validate); // Used to validate when user moves off of each element
input.addEventListener("input", validate); // Used to validate as data is being entered
});
function validate() {
// Keep track of whether the form is valid or not. Assume that it is by default
var valid = true;
// .innerHTML is for when you want to assign a string containing
// HTML to a DOM element. This invokes the HTML parser and renders
// the HTML. If you don't have HTML in the string, use .textContent
// instead, which doesn't invoke the HTML parser and is more efficient
// See if the password was typed in both boxes before telling the user
// that the passwords don't match
if(p1.value && p2.value){
// Are they the same?
if(p1.value !== p2.value){
feedback.textContent = "passwords dont match";
valid = false;
} else {
feedback.textContent = "passwords match";
}
} else {
// If both password fields aren't filled in, the form can't be valid
valid = false;
}
if(p1.value === "") {
feedback.textContent = "Must have a password";
valid = false;
}
// Send a result to the caller so it can be known by other code if the form is valid
return valid;
}
<div class = "mainInfo">
<form name="SignUpForm" action="signUpHandler.php" method='POST' class="inputLists">
<div>username: <input type="text" name="userName"></div>
<div>password: <input id="p1" type="password" name="password"></div>
<div>reenter password: <input id="p2" type="password" name="passwordConfirmation"></div>
<!-- Any form element that has a "name" attribute will submit its name/value as
part of the form data when the form gets submitted. You probably don't want
the actual submit button to be included in this, so don't give the button
a "name" attribute. -->
<input type="submit" value="submit"> <input type="reset" value="reset">
</form>
<div id="feedback"></div>
</div>

onSubmit button won't load location

I switched from type=click to type=submit so that I can use the Enter key to login. The if/else statements for invalid username/password functions fine. But if I input the correct credentials it wont load the location(different HTML page.)
PS: I'm new to coding in general(only 3 weeks in) Try to explain it so a newbie would know.
Thanks in advance.
<script type="text/javascript">
function check_info(){
var username = document.login.username.value;
var password = document.login.password.value;
if (username=="" || password=="") {
alert("Please fill in all fields")
} else {
if(username=="test") {
if (password=="test") {
location="Random.html"
} else {
alert("Invalid Password")
}
} else {
alert("Invalid Username")
}
}
}
</script>
<form name=login onsubmit="check_info()">
Username:
<input type="text" name="username" id="username"/>
<br>
Password:
<input type="password" name="password" id="password"/>
<br>
<br>
<input type="submit" value="Login"/>
</form>
You need to use .href on location
location.href = "Random.html";
(Also, since you said you were new, be sure to keep your dev console (F12) open when writing JavaScript and testing - you'll catch a lot of errors very early on)
Two things:
1 - Proper way to simulate a clink on a link is to use change the href attribute of location, not location itself. The line below should work:
window.location.href = "Random.html";
2 - As you are redirecting to another page, you have to "suppress" (stop) the natural onsubmit event.
In other words, you have to return false on the onsubmit event, otherwise the redirection (to Random.html) won't have a chance to work because the submit event will kick in (and sedn the user to the action page of the form) before the redirection works.
So change <form name=login onsubmit="check_info()"> to:
<form name=login onsubmit="return check_info()">
And add a return false; to the end of check_info().
The full code should be as follows:
<script type="text/javascript">
function check_info(){
var username = document.login.username.value;
var password = document.login.password.value;
if (username=="" || password=="") {
alert("Please fill in all fields")
} else {
if(username=="test") {
if (password=="test") {
window.location.href = "Random.html"; // ------ CHANGED THIS LINE
} else {
alert("Invalid Password")
}
} else {
alert("Invalid Username")
}
}
return false; // ------------------------ ADDED THIS LINE
}
</script>
And the HTML (only the onsubmit changed):
<form name="login" onsubmit="return check_info()">
Username:
<input type="text" name="username" id="username"/>
<br>
Password:
<input type="password" name="password" id="password"/>
<br>
<br>
<input type="submit" value="Login"/>
</form>
JSFiddle demo here.
The new way of doing this - set a breakpoint at the line
if(username=="test") {
And step through it to find what the problem is.
The old school way of doing this (from back before we had Javascript debuggers) is to alert messages in each of those blocks, and figure out why you step into that block to begin with. It's a lot more cumbersome than the debugger, but sometimes you may need to resort to old school hacks.

Validate HTML form input with JavaScript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Validate email address in Javascript?
I have an HTML form that uses PHP/MySQL to post to a database. In the email section of the form, I want the user to be displayed an error message if he or she types in an email address that is not in valid email address format. I am modeling off of a code like this, but I cannot get it work.
Note that whenever I hit the submit button on the form, the form submits, and the PHP action works fine. The problem is I can enter anything I like in the form and it will pass fine. I would like for it to display the error message "Not a valid email address". I understand I can validate via PHP too, but I would like to validate on the client side as well.
Can anyone assist?
<script type="text/javascript">
function validateEmail()
{
var x=document.forms["test"]["email"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
</script>
<form name"test" action="roads.php" onsubmit="return validateEmail();" method="post">
<input type="text" name="email" placeholder="Enter your e-mail" />
<input type="submit" value="Show Me!" />
</form>
you are missing a = in html, which doesn't make to form name test..and javascript can't find the form of name test, and throws error...check console log for javascript errors..
<form name"test" action="roads.php" onsubmit="return validateEmail();" method="post">
<form name="test" action="roads.php" onsubmit="return validateEmail();" method="post">
Working code
Here is a better way to access the form and its fields - also remember to return true
Assuming <form id="testform" action="roads.php" method="post">
we can use unobtrusive scripting
<script>
window.onload=function() {
document.getElementById("testform").onsubmit=function () {
var email=this.email.value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length) {
alert("Not a valid e-mail address");
return false;
}
return true;
}
}
</script>

javascript - why doesnt this work?

<form method="post" action="sendmail.php" name="Email_form">
Message ID <input type="text" name="message_id" /><br/><br/>
Aggressive conduct <input type="radio" name="conduct" value="aggressive contact" /><br/><br/>
Offensive conduct <input type="radio" name="conduct" value="offensive conduct" /><br/><br/>
Rasical conduct <input type="radio" name="conduct" value="Rasical conduct" /><br/><br/>
Intimidating conduct <input type="radio" name="conduct" value="intimidating conduct" /><br/><br/>
<input type="submit" name="submit" value="Send Mail" onclick=validate() />
</form>
window.onload = init;
function init()
{
document.forms["Email_form"].onsubmit = function()
{
validate();
return false;
};
}
function validate()
{
var form = document.forms["Email_form"]; //Try avoiding space in form name.
if(form.elements["message_id"].value == "") { //No value in the "message_id"
box
{
alert("Enter Message Id");
//Alert is not a very good idea.
//You may want to add a span per element for the error message
//An div/span at the form level to populate the error message is also ok
//Populate this div or span with the error message
//document.getElementById("errorDivId").innerHTML = "No message id";
return false; //There is an error. Don't proceed with form submission.
}
}
}
</script>
Am i missing something or am i just being stupid?
edit***
sorry i should add! the problem is that i want the javascript to stop users going to 'sendmail.php' if they have not entered a message id and clicked a radio button... at the moment this does not do this and sends blank emails if nothing is inputted
You are using
validate();
return false;
...which means that the submit event handler always returns false, and always fails to submit. You need to use this instead:
return validate();
Also, where you use document.forms["Email form"] the space should be an underscore.
Here's a completely rewritten example that uses modern, standards-compliant, organised code, and works:
http://jsbin.com/eqozah/3
Note that a successful submission of the form will take you to 'sendmail.php', which doesn't actually exist on the jsbin.com server, and you'll get an error, but you know what I mean.
Here is an updated version that dumbs down the methods used so that it works with Internet Explorer, as well as includes radio button validation:
http://jsbin.com/eqozah/5
You forgot the underscore when identifying the form:
document.forms["Email_form"].onsubmit = ...
EDIT:
document.forms["Email_form"].onsubmit = function() {
return validate();
};
function validate() {
var form = document.forms["Email_form"];
if (form.elements["message_id"].value == "") {
alert("Enter Message Id");
return false;
}
var conduct = form.elements['conduct']; //Grab radio buttons
var conductValue; //Store the selected value
for (var i = 0; i<conduct.length; i++) { //Loop through the list and find selected value
if(conduct[i].checked) { conductValue = conduct[i].value } //Store it
}
if (conductValue == undefined) { //Check to make sure we have a value, otherwise fail and alert the user
alert("Enter Conduct");
return false;
}
return true;
}
return the value of validate. Validate should return true if your validation succeeds, and false otherwise. If the onsubmit function returns false, the page won't change.
EDIT: Added code to check the radio button. You should consider using a javascript framework to make your life easier. Also, you should remove the onclick attribute from your submit input button as validation should be handled in the submit even, not the button's click
Most obvious error, your form has name attribute 'Email_form', but in your Javascript you reference document.forms["Email form"]. The ironic thing is, you even have a comment in there not to use spaces in your form names :)

Categories

Resources