JS verify login form - where I went wrong? - javascript

I have nut to crack, that cracks my head for some time now.
I'm programming beginner, that's for introducing. I try to achieve JS form validation, that checks input fields email and password and if it match some criteria, unset "disabled" attribute on login button.
I tried components of my JS code and it works just fine, but when I merge it into function validate(), it just dont works and I cannot find reason why.
Here is my HTML:
<!DOCTYPE html>
<head>
<meta charset='UTF-8' />
<title>$title</title>
<link href='css/style.css' rel='stylesheet' type='text/css' />
<script type='text/javascript' charset='utf-8' src='js/validateInput.js'></script>
</head>
<body>
<div id='header'><h1>$title<h1></div>
<form name='login' method='post' action=''>
<table border='0'>
<tr>
<th>E-mail:</th>
<td colspan='2'><input type='text' name='email' id='email' size='30' value='$posted_email'
onkeyup='validate()' onclick='validate()' onchange='validate()' />
</td>
</tr>
<tr>
<th>Heslo:</th>
<td><input type='password' name='pword' id='pword' size='21'
onkeyup='validate()' onclick='validate()' onchange='validate()'/></td>
<td><input type='submit' name='login' class='submit' id='loginBtn' value='OK' /></td>
</tr>
</table>
</form>
</body>
Now my JS:
function $(id) {
if (id.indexOf('#') == 0 || id.indexOf('.') == 0) {
var name = id.substr(1);
return id.indexOf('#') == 0 ? document.getElementById(name) : document.getElementsByClassName(name);
}
return (typeof document.getElementById('id') !== 'undefined') ? document.getElementById(id) : document.getElementsByClassName(id);
}
function validateEmail(string) {
var re = /[\w\s\.\$\*\+\/\?\^\{\|\}\(\)]{1,64}#[\w]{1,250}\.[\w]{2,3}/;
return re.test(string);
}
function validate() {
var login = $('#loginBtn');
var email = $('#email');
var pword = $('#pword');
if (!validateEmail(email.value)) {
email.style.color = 'orange';
} else if (pword.length > 0) {
login.disabled = false;
}
return false;
}
window.onload = function() {$('#loginBtn').disabled = true;};
Any thoughts?

The problem is located at this condition :
if (!validateEmail(email.value)) {
email.style.color = 'orange';
} else if (pword.length > 0) {
login.disabled = false;
}
Change your function validate() to below :
function validate() {
var login = $('#loginBtn');
var email = $('#email');
var pword = $('#pword');
var result = false;
if (!validateEmail(email.value)) {
email.style.color = 'orange';
} else {
email.style.color = 'black';
result = true;
}
if (result && pword.value.length > 0) {
login.disabled = false;
} else {
login.disabled = true;
}
}
Fiddle demo.
Hopefully this help.

Related

Java Script Functions Don't work and How do i add my javascript file to html and get it to work

I have my javascript file and code done, called script.js and I've added it to my HTML file. I'm very new to this and I'm not sure if I'm doing it right. the functions don't seem to work either. I am very lost and would just like yo figure it out. thank you.
this is my javascript file called (script.js)
$(document).ready(function () {
//When add database, will pull total from database
var total = 30;
var totalTax = total * 0.8;
var totalShip = total * 0.3;
var totalAll = total + totalTax + totalShip;
document.getElementById("totalShop").innerHTML = total;
document.getElementById("totalTax").innerHTML = totalTax;
document.getElementById("shipping").innerHTML = totalShip;
document.getElementById("totalDue").innerHTML = totalAll;
});
function applyActiveCss(id) {
for (var i = 0; i < document.links.length; i++) {
if (document.links[i].id == id) {
document.links[i].className = 'active';
}
else {
document.links[i].className = 'links';
}
}
}
function validateCheckout() {
if (document.checkoutForm.cardNumber.value == "") {
alert("Please provide card number");
document.checkoutForm.cardNumber.focus();
return false;
}
if (document.checkoutForm.month.value == "" || isNaN(document.checkoutForm.month.value) ||
document.checkoutForm.month.value.length != 2) {
alert("Please provide your month");
document.checkoutForm.month.focus();
return false;
}
if (document.checkoutForm.year.value == "" || isNaN(document.checkoutForm.year.value) ||
document.checkoutForm.year.value.length != 4) {
alert("Please provide your month");
document.checkoutForm.year.focus();
return false;
}
return (true);
}
function validateUserInfo() {
if (document.userInfo.fullname.value == "") {
alert("Please provide full name");
document.checkoutForm.cardNumber.focus();
return false;
}
if (document.userInfo.email.value == "") {
alert("Please provide your Email!");
document.userInfo.email.focus();
return false;
}
var emailID = document.userInfo.email.value;
var atpos = emailID.indexOf("#");
var dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || (dotpos - atpos < 2)) {
alert("Please enter correct email ID")
document.userInfo.email.focus();
return false;
}
if (document.userInfo.zipcode.value == "" ||
isNaN(document.userInfo.zipcode.value) ||
document.userInfo.zipcode.value.length != 5) {
alert("Please provide a zip in the format 12345");
document.userInfo.zipcode.focus();
return false;
}
var phoneID = document.userInfo.phone.value;
var dashpos1 = phoneID.indexOf("-");
var dashpos2 = phoneID.lastIndexOf("-");
for (var i = 3; i < 7; i++) {
phoneID[i] = phoneID[i + 1];
}
for (var j = 6; j < 8; j++) {
phoneID[j] = phoneID[j + 2];
}
if (document.userInfo.phone.value == "" ||
document.userInfo.phone.value.length != 12
|| dashpos1 != 3 || dashpos2 != 7 || isNaN(phoneID)) {
alert("Please provide a phone number in the format 123-456-7890");
document.userInfo.phone.focus();
return false;
}
return (true);
}
and this is part of my HTML file called (userinfo.html)
¿<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Personal Information</title>
<link rel="stylesheet" type="text/css" href="StyleSheet1.css">
</head>
<body>
<script src="script.js"> </script>
<h1>User Information</h1>
<p>Please fill out the following information.</p>
<!--<form class="" action="submit.php" method="post">-->
<form action=".shipinfo.html" name="userInfo" onsubmit="return (validateUserInfo());">
<table>
<tbody>
<tr>
<td>
Full Name: <br>
<input type="text" maxlength="100" name="fullname" required>
</td>
<td>
Phone Number: <br>
<input type="number" minlength = "12" maxlength="12" name="phone"
placeholder="123-456-7890">
</td>
</tr>
<tr>
<td>
Address Line 1: <br>
<input type="text" maxlength="100" name="add1" required>
</td>
<td>
Address Line 2: <br>
<input type="text" maxlength="100" name="add2">
</td>
</tr>
<tr>
<td>
City: <br>
<input type="text" maxlength="100" name="city" required>
</td>
I dont see the following jquery script in your file (so it does not read the document ready part and you do not see the 'document loaded' in your console.
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
Another error you are getting in the console is 'Cannot read property 'innerHTML' of null' for this:
document.getElementById("totalShip").innerHTML = total;
This happens when the element, in this case 'totalship', is not accessible or available in your webpage and as such its property cannot be read. Since you are accessing an id, can you provide your css file here?
In addition, where is the access to your database through these files (.userInfo, .checkoutForm etc.) are not accessible via your files as of now.

Form Validation Error(Beginner)

I am beginning with JavaScript. I just wrote a code for form validation but the checkfields() function is not working. I tried to find the error but couldn't spot it after several attempts. It will be very helpful if someone out there can point out the error.
<html>
<title> Sign-Up </title>
<head>
<style>
body {
background-color: lightblue;
}
input {
height: 30px;
widht: 100px;
}
</style>
<script>
function valform() {
var x = document.forms["f2"]["fn"].value;
var y = document.forms["f2"]["ln"].value;
var z = document.forms["f2"]["eid"].value;
var a = document.forms["f2"]["pass"].value;
var b = document.forms["f2"]["cpass"].value;
if (x == "" || y == "" || z == "" || a == "" || b == "") {
alert("Please fill the form completely");
}
}
function checkfields() {
var p1 = document.forms["f2"]["pass"].value;
var p2 = document.forms["f2"]["cpass"].value;
if (p1 != p2) {
document.getElementByID("message").innerHTML = "Password Doesn't match";
return false;
}
}
</script>
</head>
<body>
<center>
<h1> Sign-Up </h1>
<form name="f2" onsubmit="return checkfields()">
First-Name: <input type="text" name="fn"> Last-Name :<input type="text" name="ln"><br><br><br> Email-Id:
<input type="text" name="eid"><br><br><br> Password:
<input type="password" name="pass"><br><br><br> Confirm-Password
<input type="password" name="cpass">
<span id='message'></span>
<br><br><br>
<input type="Submit" onclick="valform()" value="Submit">
</form>
</center>
</body>
</html>
Two things, you need to prevent the default submit event...
<form name="f2" id="myForm" onsubmit="event.preventDefault(); checkfields()">
Note.. I also gave your form an ID which will be needed for the next step...
I also removed the onclick from the submit button...
<input type="Submit"value="Submit">
I modified your method to return a boolean depending on the validation result
function valform() {
var x = document.forms["f2"]["fn"].value;
var y = document.forms["f2"]["ln"].value;
var z = document.forms["f2"]["eid"].value;
var a = document.forms["f2"]["pass"].value;
var b = document.forms["f2"]["cpass"].value;
if (x == "" || y == "" || z == "" || a == "" || b == "") {
alert("Please fill the form completely");
return false;
}
return true;
}
and I call it within checkfields method where upon being success I submit the form using the ID we assigned above...
function checkfields() {
var p1 = document.forms["f2"]["pass"].value;
var p2 = document.forms["f2"]["cpass"].value;
if (p1 != p2) {
document.getElementById("message").innerHTML = "Password Doesn't match";
return false;
}
if(valform()){
document.getElementById("myForm").submit();
}
}
Here's a little JSFiddle demonstrating the above.
Note: you had one error getElementByID should be lower case d (getElementById)
There is a js error, getElementByID should be getElementById
Also I have modified how the validations goes below
You don't need the click handler on the submit, the return is enough on the onsubmit.
Onsubmit calls valform, and all validation is done within. Since you have a checkfields function already, you can simply call it in the validation function.
You also need to return false if the form is incomplete or else it's going to submit anyway. You could make the code a bit cleaner as well by caching document.forms["f2"] into a variable
You also had a typo in the css widht: 100px;
// saving form into a variable to make it a bit cleaner below
var form_f2 = document.forms["f2"];
function checkfields() {
var p1 = form_f2["pass"].value;
var p2 = form_f2["cpass"].value;
if (p1 != p2) {
document.getElementById("message").innerHTML = "Password Doesn't match";
return false;
}
}
function valform() {
var x = form_f2["fn"].value;
var y = form_f2["ln"].value;
var z = form_f2["eid"].value;
var a = form_f2["pass"].value;
var b = form_f2["cpass"].value;
// call to check passwords
checkfields();
if (x == "" || y == "" || z == "" || a == "" || b == "") {
alert("Please fill the form completely");
// need to return false due to incomplete form
return false;
}
}
body {
background-color: lightblue;
}
input {
height: 30px;
width: 100px;
}
<center>
<h1> Sign-Up </h1>
<form name="f2" onsubmit="return valform()">
First-Name: <input type="text" name="fn"> Last-Name :<input type="text" name="ln"><br><br><br> Email-Id:
<input type="text" name="eid"><br><br><br> Password:
<input type="password" name="pass"><br><br><br> Confirm-Password
<input type="password" name="cpass">
<span id='message'></span>
<br><br><br>
<input type="Submit" value="Submit">
</form>
</center>
You could actually combine the checkfields function content into valform. I don't see any need for the extra function in the given code
In your valform() function you need to pass in the event object to prevent submission of the form is validation does not pass with event.preventDefault(). Also, document.getElementByID should be document.getElementById.
<html>
<title> Sign-Up </title>
<head>
<style>
body {
background-color: lightblue;
}
input {
height: 30px;
widht: 100px;
}
</style>
<script>
function valform(e) {
var x = document.forms["f2"]["fn"].value;
var y = document.forms["f2"]["ln"].value;
var z = document.forms["f2"]["eid"].value;
var a = document.forms["f2"]["pass"].value;
var b = document.forms["f2"]["cpass"].value;
if (x == "" || y == "" || z == "" || a == "" || b == "") {
alert("Please fill the form completely");
e.preventDefault();
}
}
function checkfields() {
var p1 = document.forms["f2"]["pass"].value;
var p2 = document.forms["f2"]["cpass"].value;
if (p1 != p2) {
document.getElementById("message").innerHTML = "Password Doesn't match";
return false;
}
return true;
}
</script>
</head>
<body>
<center>
<h1> Sign-Up </h1>
<form name="f2" onsubmit="return checkfields()">
First-Name: <input type="text" name="fn"> Last-Name :<input type="text" name="ln"><br><br><br> Email-Id:
<input type="text" name="eid"><br><br><br> Password:
<input type="password" name="pass"><br><br><br> Confirm-Password
<input type="password" name="cpass">
<span id='message'></span>
<br><br><br>
<input type="Submit" onclick="valform(event)" value="Submit">
</form>
</center>
</body>
</html>

After submit a form, stay same page, show a word in the page

After clicking "submit", stay on the page.
Input data, like "computer number" and "profit", stay inside those blank square.
A word "Submitted", appear in the center of this page.
The following is my code, Please help, thank you!
<html>
<head>
<title></title>
</head>
<body>
<form name="form"
onsubmit="return validateForm()">
Computer Number:<br>
<input type="text" name="Computer" required><br>
<p>How much is your profit?
<input id="id1" name = "id1" required>
<button type = "button" onclick="myFunction()">My Answer</button>
<button type="button" id="btn1" onclick="Solution()" style="display:none;">Solution</button>
</p>
<p id="Q1"></p>
<script>
var errosCount = 0;
function myFunction() {
var x, text;
x = document.getElementById("id1").value;
if (isNaN(x) || x != 100) {
text = "Incorrect"; document.getElementById("Q1").style.color = "red";errosCount++;
} else {
text = "Correct"; document.getElementById("Q1").style.color = "green";
}
document.getElementById("Q1").innerHTML = text;
if(errosCount === 3){
errosCount = 0;
document.getElementById('btn1').style.display = 'block';
document.getElementById("Q1").innerHTML = '';
} else {
document.getElementById('btn1').style.display = 'none';
}
}
function Solution(){
text = "(P - w) * q<sub>o</sub> - I = (53 - 43) * 30 - 200 = 100"; document.getElementById("Q1").style.color = "red";
document.getElementById("Q1").innerHTML = text;
}
</script>
<input type="submit" value="Submit">
</form>
<script>
function validateForm() {
var q = document.forms["my form"]["Computer"].value;
if (q == "") {
alert("Computer Number is Missing!");
return false;}
var w = document.forms["my form"]["id1"].value;
if (w != "100") {
alert("Question 1 is Incorrect!");
return false;}
}
</script>
</body>
</html>
Firstly, you were having document.forms["my form"] which was invalid since your form name was form so I changed it to document.forms["form"].
And, on submit, I added return false at the bottom of the function to stay on the page. Also, before that, added "Submitted" text in the center of the page as shown below.
Here's working code snippet!
Hope that helps!
var errosCount = 0;
function myFunction() {
var x, text;
x = document.getElementById("id1").value;
if (isNaN(x) || x != 100) {
text = "Incorrect";
document.getElementById("Q1").style.color = "red";
errosCount++;
} else {
text = "Correct";
document.getElementById("Q1").style.color = "green";
}
document.getElementById("Q1").innerHTML = text;
if (errosCount === 3) {
errosCount = 0;
document.getElementById('btn1').style.display = 'block';
document.getElementById("Q1").innerHTML = '';
} else {
document.getElementById('btn1').style.display = 'none';
}
}
function Solution() {
text = "(P - w) * q<sub>o</sub> - I = (53 - 43) * 30 - 200 = 100";
document.getElementById("Q1").style.color = "red";
document.getElementById("Q1").innerHTML = text;
}
function validateForm() {
var q = document.forms["form"]["Computer"].value;
if (q == "") {
alert("Computer Number is Missing!");
return false;
}
var w = document.forms["form"]["id1"].value;
if (w != "100") {
alert("Question 1 is Incorrect!");
return false;
}
document.getElementById("submitted").innerHTML = "Submitted"
return false;
}
#submitted {
text-align: center
}
<form name="form" onsubmit="return validateForm()">
Computer Number:<br>
<input type="text" name="Computer"><br>
<p>How much is your profit?
<input id="id1" name="id1" required>
<button type="button" onclick="myFunction()">My Answer</button>
<button type="button" id="btn1" onclick="Solution()" style="display:none;">Solution</button>
</p>
<p id="Q1"></p>
<input type="submit" value="Submit">
</form>
<br/>
<div id="submitted">
</div>
Hello you should think abut using AJAX as you are sending a form.
This can be the button:
<button type="button"
onclick="validateForm('ajax_info.php', myFunction)"> Clic to Submit
</button>
And this the AJAX function:
function validateForm(url, cFunction) {
var xhttp;
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}
};
xhttp.open("GET", url, true); //can be POST
xhttp.send();
}
function myFunction(xhttp) {
document.getElementById("submited").innerHTML =
xhttp.responseText;
}

Running ajax query after validation

I have an ajax insert script and a validation script.
But the insert script is always working, so even if the validation sends a message that some fields are wrong, it still uploads the data.
How do I change my code so that the insert query only runs after the validation?
My code:
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css">
<meta charset="utf-8">
<title>Form</title>
</head>
<script type="text/javascript" src="js/validate.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<body>
<div id="wrap">
<table>
<td>
<form name="form">
<tr>
<p class="names">Voornaam:</p> <p><input type="text" name="voornaam" id="voornaam"></p>
</tr>
<tr>
<p class="names">Achternaam:</p> <p><input type="text" name="achternaam" id="achternaam"></p>
</tr>
<tr>
<p class="names">Telefoonnummer:</p> <p><input type="text" name="telefoonnummer" id="telefoonnummer"></p>
</tr>
<tr>
<p class="names">Emailadres:</p> <p><input type="text" name="email" id="email"></p>
</tr>
<tr>
<input class="knop" type="submit" name="insert" value="Opsturen" id="insert">
</tr>
</form>
</td>
</table>
<br>
<div id="berichten">
</div>
<script>
var validator = new FormValidator('form', [{
name: 'voornaam',
display: 'Voornaam',
rules: 'required'
}, {
name: 'achternaam',
display: 'achternaam',
rules: 'required'
},{
name: 'telefoonnummer',
display: 'telefoon',
rules: 'required|numeric'
},{
name: 'email',
display: 'email',
rules: 'required|valid_email'
}], function(errors, event) {
var berichten = document.getElementById('berichten');
berichten.innerHTML = '';
if (errors.length > 0) {
for (var i = 0, l = errors.length; i < l; i++) {
berichten.innerHTML += errors[i].message + '<br>';
}
}
});
</script>
<script type="text/javascript">
$(function(){
$('#insert').click(function(){
var voornaam = $('#voornaam').val();
var achternaam = $('#achternaam').val();
var telefoonnummer = $('#telefoonnummer').val();
var email = $('#email').val();
$.post('action.php',{action: "button", voornaam:voornaam, achternaam:achternaam, telefoonnummer:telefoonnummer, email:email},function(res){
$('#result').html(res);
});
document.getElementById('berichten').innerHTML = 'Verstuurd!';
});
});
</script>
</div>
</body>
</html>
I think you should be sending the ajax call in the FormValidator callback if there are no errors.
function(errors, event) {
var berichten = document.getElementById('berichten');
berichten.innerHTML = '';
if (errors.length > 0) {
for (var i = 0, l = errors.length; i < l; i++) {
berichten.innerHTML += errors[i].message + '<br>';
}
} else {
var voornaam = $('#voornaam').val();
var achternaam = $('#achternaam').val();
var telefoonnummer = $('#telefoonnummer').val();
var email = $('#email').val();
$.post('action.php',{action: "button", voornaam:voornaam, achternaam:achternaam, telefoonnummer:telefoonnummer, email:email},function(res){
$('#result').html(res);
});
document.getElementById('berichten').innerHTML = 'Verstuurd!';
}
}
http://rickharrison.github.io/validate.js/
Before formValidator add is_valid = true :
var is_valid = true;
var validator = new FormValidator.....
In event error add is_valid = false if length > 0 :
function(errors, event) {
var berichten = document.getElementById('berichten');
berichten.innerHTML = '';
if (errors.length > 0) {
is_valid = false;
}
Finally :
$('#insert').click(function(){
if(is_valid){
// is valid, do code here
}
});

placeholder works for text but not password box in IE/Firefox using this javascript

Js File
//Modified from http://www.beyondstandards.com/archives/input-placeholders/
function activatePlaceholders()
{
var detect = navigator.userAgent.toLowerCase();
if (detect.indexOf("safari") > 0) return false;
var inputs = document.getElementsByTagName("input");
for (var i=0;i<inputs.length;i++)
{
if (inputs[i].getAttribute("type") == "text")
{
var placeholder = inputs[i].getAttribute("placeholder");
if (placeholder.length > 0)
{
inputs[i].value = placeholder;
inputs[i].onclick = function()
{
if (this.value == this.getAttribute("placeholder"))
{
this.value = "";
}
return false;
}
inputs[i].onblur = function()
{
if (this.value.length < 1)
{
this.value = this.getAttribute("placeholder");
}
}
}
}
else if (inputs[i].getAttribute("type") == "password")
{
var placeholder = inputs[i].getAttribute("placeholder");
if (placeholder.length > 0)
{
inputs[i].value = placeholder;
inputs[i].onclick = function()
{
if (this.value == this.getAttribute("placeholder"))
{
this.value = "";
}
return false;
}
inputs[i].onblur = function()
{
if (this.value.length < 1)
{
this.value = this.getAttribute("placeholder");
}
}
}
}
}
}
window.onload = function()
{
activatePlaceholders();
}
Html part
<form name="input" action="login.php" method="post">
<table width="*" border="0">
<tr>
<td align="left"><input type="text" name="username" placeholder="Username" /> <input type="password" name="pass" placeholder="Password" /><input type="submit" value="Login" /></td>
</tr>
<tr>
<td colspan="2" align="right">Stay logged in: <input type="checkbox" name="remember" value="1"> Sign Up | Forgot Password </td>
</tr>
</table>
</form>
This works for the input box. Not working for the password box. It wants to star out the place holder text on the password. I want to users password to be started out but not the place holder. Not sure how to fix that so it works in IE and Firefox.
var passwords = document.getElementsByTagName("password");
Should be:
var passwords = document.getElementsByTagName("input");
As it's <input type="password"> not <password...>. However, I don't think that will help you in this case, because when you set the value of the password, all you'll see are the black dots/asterisks.

Categories

Resources