How come my JavaScript isn't working? - javascript

I am doing a login page for school. I have written the page, but the JavaScript does not seem to work with the form. I have checked over both the form and the JavaScript multiple times, but I see no mistake. Can anyone help me?
function processInfo() {
var theusername;
var thepassword;
theusername = document.myForm.username.value;
thepassword = document.myForm.password.value;
if (document.myForm.username.value = "") {
alert("Please enter in the username.")
return false;
} else if (document.myForm.password = "") {
alert("Please enter in the password.")
return false;
} else if (document.myForm.username.value != "andrew123") {
document.myForm.txtOutput.value = "Incorrect username or password."
} else if (thepassword != "abc") {
document.myForm.txtOutput.value = "Incorrect username or password."
} else if (theusername == "andrew123"
thepassword == "abc") {
document.myForm.txtOutput.value = "Correct! You have successfully logged in."
}
}
<form name="myForm">
<b>User Name:</b>
<input type="text" name="username" size="36" maxlength="100">
<b>Password:</b>
<input type="text" name="password" size="36" maxlength="100">
<p>
<input type=button value="VERIFY INFORMATION" onClick=processInfo()>
</p>
<textarea name="txtOutput" rows=1 cols=4 0></textarea>
</form>

= is an assignment, you keep using it when you are trying to perform a comparison (which would use == or ===).
Sometimes you try to compare the form control with a string instead of getting its .value.
You forgot to put a boolean AND between the two conditions you have theusername == "andrew123"
thepassword == "abc"
You should learn to use the console in your browser as most of these problems would be highlighted in it or could be with the addition of a little logging.

Related

Text obtained with innerHTML dissapear

I have the following code:
function passVerif() {
if (document.forms['form'].pass.value === "") {
messagePV.innerHTML = ("Password field is empty!")
//alert("Password field is empty!");
return false;
}
return true;
}
function emailVerif() {
if (document.forms['form'].email.value === "") {
messageEV.innerHTML = ("Email field is empty!")
//alert("Email field is empty!");
return false;
}
return true;
}
function validate() {
var email = document.getElementById("input").value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (!emailFilter.test(email)) {
messageV.innerHTML = ("Please enter a valid e-mail address!")
//alert('Please enter a valid e-mail address!');
return false;
}
}
<div>
<form name="form"> Login<br>
<input type="text" name="email" placeholder="Enter email here" id="input" class="input">Email address<br>
<input type="password" name="pass" placeholder="Enter password here" class="input">Password<br>
<input type="button" name="required" onclick="return passVerif(), emailVerif(), validate()">
</form>
</div>
<div id="messagePV"></div>
<div id="messageEV"></div>
<div id="messageV"></div>
As you can see, input type is submit. Because of that (page is refreshing after click on button) the text I want to show disappears after refresh.
As I read on other posts, the simple change from submit to button will do the dew.
But I am suspecting that I messed up the return false and return true instructions in all of my functions.
Is this correct? If they are in a logical way I can avoid the page refresh and continue to use submit? At least until all conditions are met and the form is good to go.
In other words, can someone help me to put return false and true in such way that the page will refresh only if all conditions are met.
Thanks a lot, I am not even a noob.
Codes are copied from different sources on the internet. I am at the very beginning of coding road. Please have mercy :)
I would change it to one validation function and have a bool that is returned based on if it has errored or not:
// Just have one validation function
function validate() {
var errorMessage = ''; // build up an error message
var email = document.forms['form'].email.value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (email === "") {
errorMessage += "Email field is empty!<br>";
} else if (!emailFilter.test(email)) { // this can be else if
errorMessage += "Please enter a valid e-mail address!<br>";
}
if (document.forms['form'].pass.value === "") {
errorMessage += "Password field is empty!<br>"
}
if (errorMessage === '') {
return true; // return true as no error message
} else {
document.getElementById('error-message').innerHTML = errorMessage; // show error message and return false
return false;
}
}
<div>
<form name="form"> Login<br>
<input type="text" name="email" placeholder="Enter email here" id="input" class="input">Email address<br>
<input type="password" name="pass" placeholder="Enter password here" class="input">Password<br>
<input type="submit" name="required" onclick="return validate();">
</form>
</div>
<div id="error-message">
<!-- CAN HAVE ONE ERROR MESSAGE DIV -->
</div>
I tried with your code and I could find the the messages were not getting updated based on the conditions. So I did few modifications to your code to display the message based on which condition fails.
HTML
<div>
<form name="form"> Login<br>
<input type="text" name="email" placeholder="Enter email here" id="input" class="input">Email address<br><br>
<input type="password" name="pass" placeholder="Enter password here" class="input">Password<br><br>
<input type="submit" name="required" value="Submit" onclick="return passVerif(), emailVerif(), validate()">
</form>
</div>
<div id="messagePV"></div>
<div id="messageEV"></div>
<div id="messageV"></div>
JS
function passVerif() {
messagePV.innerHTML = ("")
if(document.forms['form'].pass.value === "") {
messagePV.innerHTML = ("Password field is empty!")
//alert("Password field is empty!");
return false;
}
return true;
}
function emailVerif() {
messageEV.innerHTML = ("")
if(document.forms['form'].email.value === "") {
messageEV.innerHTML = ("Email field is empty!")
//alert("Email field is empty!");
return false;
}
return true;
}
function validate() {
messageV.innerHTML = ("")
var email = document.getElementById("input").value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (!emailFilter.test(email)) {
messageV.innerHTML = ("Please enter a valid e-mail address!")
//alert('Please enter a valid e-mail address!');
return false;
}
}
By initializing the errormessage filed to empty sting u can maintain the fresh set of error messages.
Jsfiddle: https://jsfiddle.net/85w7qaqx/1/
Hope this helps out.

if else loop issue

I've been working on a login form which I've been trying to wrap my head around. Essentially, the if() statement isn't doing what I expect. Even if the core.user/core.pass exactly match the set values, it's not getting to the success case.
function validateLoginForm()
{
//var x = document.forms["myForm"]["username"].value;
//var y = document.forms["myForm"]["password"].value;
"use strict";
var username = document.forms["myForm"]["username"].value;
var password = document.forms["myForm"]["password"].value;
console.log("username:" + username);
console.log("password:" + password);
var coreUser = "testUser";
var corePass = "testPass";
if (username.value === coreUser) {
console.log("username matches");
if(password.value === corePass) {
console.log("You are logged in as " + username.value);
}
else {
alert("Password invalid");
}
}
else {
alert("Username invalid");
}
}
<div class="loginPage">
<div name="myForm" class="form">
<div id ="login">
<form class="login-form" name="myForm">
<h2>Login Page</h2>
<input name="username" id="username" type="text" placeholder="enter username"/>
<input name="password" id="password" type="password" placeholder="enter password"/>
<button type="button" onclick="validateLoginForm()">login</button>
<p class="message">Don't have an account? Register</p>
</form>
</div>
</div>
</div>
password and username already contains the value. So you are trying to call .value on a string which returns undefined. Just remove the .value when you are using the password and username variables like this.
if (username === coreUser) {
//...
if(password === corePass) {
//...
Also, this kind of bug is easilly found with a debugger. You should take the time to learn how to use one as it will save you considerable time in the future. (every modern browser have a JS debugger in the dev tool)
You just remove .value from username.value & password.value
user like in below
username === coreUser
password === corePass
In javascript validation we should have return statement if the value is invalid.
for example :
if(username !== coreUser || username ==='') {
alert("Username invalid");
return false;
} else if(password !== corePass || password === '') {
alert("Password invalid");
return false;
} else {
console.log("username matches");
console.log("You are logged in as " + username);
}

Validating E-Mail address using JavaScript or JQuery

I have to validate E-Mail address using either JS or JQ.
Right now I am using JS but unable to pass the value of the text box as the parameter for JS. I want this to be implemented onchange.
I found solutions only using a button to validate which i don't want to.
Here is the HTML code.
<div class="form-group">
<label class="control-label">Father's E-Mail Address</label>
<input maxlength="30" pattern=".{1,50}" onchange="validateEmail(document.getElementById('txtFatherEmail').value);" title="Input Invalid" type="text" required="required" class="form-control" placeholder="Enter Father's E-Mail Address" id="txtFatherEmail" runat="server"/>
</div>
Here is the JS I have used.
function validateEmail(email) {
var emailReg = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
var valid = emailReg.test(email);
if (!valid) {
alert("False");
} else {
alert("True");
}
}
Also I would like to know if there's any better way to do this.
If I understand correctly you want to validate input as you type.
To do this you can use onkeyup event.
<div class="form-group">
<label class="control-label">Father's E-Mail Address</label>
<input maxlength="30" pattern=".{1,50}" onkeyup="validateEmail(this.value);" title="Input Invalid" type="text" required="required" class="form-control" placeholder="Enter Father's E-Mail Address" id="txtFatherEmail" runat="server"/>
</div>
Why are you using getElementById with "value"? Shouldn't you be using thee jquery syntax? Remember a jquery element is not a javasript don element. Maybe that's the trick...
function isvalid(x){
regexp1 = /#/g
gmail = /gmail.com/g
hotmail = /hotmail.com/g
if(regexp1.test(x) == true){
if(x.match(regexp1).length == 1){
x = x.split("#")
if(gmail.test(x[1]) == true){
if(x[1].match(gmail).length == 1 && x[1].length == 9){
alert("ok valid")
}else{
alert("not valid")
}
}else if(hotmail.test(x[1]) == true){
if(x[1].match(hotmail).length == 1 && x[1].length == 11){
alert("ok valid")
}else{
alert("not valid")
}
}else{
alert("no mail")
}
}else{
alert("too much #")
}
}else{
alert("no #")
}
}
this function is the jquery email check function and it just looks for gmail and hotmail and if you want just to check email from hot and gmail it is the reliable function for it

Javascript - Login Box Not Working

I am currently making a javascript and html mini-login box. I have created a javascript code which checks the length of the password and checks if confirm password and password are the same. Here is the code...
<form name = "logme">
<fieldset>
<legend>Create Your Account!</legend>
<br>
<p>Username:*<input type="text" name="user" placeholder="Enter Your Name">
<br>
<br>
Password:*<input type="password" id="pass">
<br>
<p>Confirm Password:*<input type="password" id="passwd">
<br>
<p>Email:*<input type="text" id="email" placeholder="you#example.com">
<br>
<br>
Show Password:<input id="chk" name="chk" type="checkbox" onclick="validate()" />
<br>
<br>
<input type="button" value="Create!" name="Submit" onclick="pwFunction()">
</p>
Don't Have An Account? Create One!
</fieldset>
</form>
<script>
function pwFunction() {
var password = document.getElementById('pass');
var lok = password.value.length >= 8;
var cpassword = document.getElementById('passwd');
if (!lok) {
alert('Your Password Must Have Eight Characters!');
}
return lok;
if(password.value != cpassword.value) {
alert('Your Passwords Do Not Match!');
}
}
</script>
It Only Runs The 'Your Password Must Have Eight Characters' Alert.
Why Isn't It Running Both?
Thanks For Any Answers, And Sorry For The Inconvenience.
There are a couple of error in your code / scripts:
Edit 1. Change the button to
<input type="submit" value="Create!" name="Submit" >
Edit 2. Use javascript validation on form tag
<form name = "logme" action="somewhere" onsubmit = "return pwFunction();">
This way the form is submitted only when the pwFunction() returns true.
Edit 3. Your javascript function should be:
function pwFunction() {
var password = document.getElementById('pass');
var cpassword = document.getElementById('passwd');
if (password.value.length < 8) {
alert('Your Password Must Have Eight Characters!');
return false;
}
if(password.value != cpassword.value) {
alert('Your Passwords Do Not Match!');
return false;
}
else
{
return true;
}
}
Try
if(password.value !== cpassword.value) {
alert('Your Passwords Do Not Match!');
}
Like you did, the return statement is executed always, so it causes the function to stop execution and return a result. delete the return statement:
if (!lok) {
alert('Your Password Must Have Eight Characters!');
}
if(password.value != cpassword.value) {
alert('Your Passwords Do Not Match!');
}

Javascript validation for email making issues

In my project, I am doing a JS validation for registration purpose. But the validation fails after the email validation. Upto the email validation, it works fine. But after that it is not showing any alerts for rest of validation code.
function signup() {
var signupFullName = $("#signup-full-name");
var signupName = $("#signup-login-name");
var signupEmailAddress = $("#signup-email-address");
var signupPhoneNumber = $("#signup-phone-number");
var signupPassword = $("#signup-password");
var signupConfirmPassword = $("#signup-confirm-password");
var signupAcceptTerms = $("#signup-accept-terms");
if (signupFullName[0].value == "" || signupFullName[0].value == null) {
//alert("Please enter a valid full name.");
alert("Please enter your full name");
signupFullName[0].focus();
return false;
} else if (signupName[0].value == "" || signupName[0].value == null) {
//alert("Please enter a valid login name.");
alert("Please enter your login name.");
signupName[0].focus();
return false;
} else if (signupEmailAddress[0].value == "" || signupEmailAddress[0].value == null) {
//alert("Please enter a valid email address.");
alert("Please enter your email address.");
signupEmailAddress[0].focus();
return false;
}
else if(signupEmailAddress[0].value != "") // problem in this section
{
email=signupEmailAddress[0].value;
if (!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/).test(email))
{
alert("Please enter a valid email address.");
signupEmailAddress[0].focus();
return false;
}
}
else if (signupPhoneNumber[0].value == "" || signupPhoneNumber[0].value == null) {
// alert("Please enter a valid phone number.");\
alert("Please enter your phone number.");
signupPhoneNumber[0].focus();
return false;
} else if (signupPassword[0].value == "" || signupPassword[0].value == null) {
//alert("Please enter a valid password.");
alert("Please enter your password.");
signupPassword[0].focus();
return false;
} else if (signupConfirmPassword[0].value == "" || signupConfirmPassword[0].value == null) {
alert("Please confirm the password.");
signupConfirmPassword[0].focus();
return false;
} else if (signupPassword[0].value != signupConfirmPassword[0].value) {
//alert("Please confirm the password.");
alert("Password mismatch");
signupConfirmPassword[0].focus();
return false;
} else if ($("#signup-accept-terms")[0].checked == false) {
alert("Please accept the terms and conditions.");
return false;
} else {
alert("Done");
return false;
}
}
HTML form code:
<form name="signup-form" id="signup-form" method="post" action="<?php echo $site_path; ?>/register" class="form-1" onsubmit="signup();return false;">
<p class="field">
<a href="<?php echo $root_path; ?>">
<img src="<?php echo $theme_path;?>/images/logo.png"/>
</a>
<h4 style="margin-top:10px;color:#208CCD;">Signup</h4>
<br/>
</p>
<p class="field">
<input type="text" name="signup-full-name" id="signup-full-name" placeholder="Full name">
<i class="icon-user icon-large"></i>
</p>
<p class="field">
<input type="text" name="signup-login-name" id="signup-login-name" placeholder="User name">
<i class="icon-signin icon-large"></i>
</p>
<p class="field">
<input type="text" name="signup-email-address" id="signup-email-address" placeholder="Email address">
<i class="icon-inbox icon-large"></i>
</p>
<p class="field">
<input type="text" name="signup-phone-number" id="signup-phone-number" placeholder="Phone number">
<i class="icon-phone icon-large"></i>
</p>
<p class="field">
<input type="password" name="signup-password" id="signup-password" placeholder="Password">
<i class="icon-lock icon-large"></i>
</p>
<p class="field" style="margin-top:10px;">
<input type="password" name="signup-confirm-password" id="signup-confirm-password" placeholder="Confirm password">
<i class="icon-lock icon-large"></i>
</p>
<p class="field">
<input type="checkbox" name="signup-accept-terms" id="signup-accept-terms" style="margin-top:10px;color:#B3B3B3">
I accept the Terms and Conditions and the Privacy Policies
</input>
</p>
<p class="submit">
<button type="submit" name="submit"><i class="icon-arrow-right icon-large"></i></button>
</p>
</form>
Can anyone help me to solve this? Thanks in advance.
As I see it it's because you use if/else to check validity of the fields.
So the code picks one error at a time - if any. While you should have something like a for-loop across all the fields you want to validate
I mean it picks this
} else if(signupEmailAddress[0].value != "") {
but does not fall into inner check anymore
if (!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/).test(email))
because email is ok now
Your problem is this statement:
else if(signupEmailAddress[0].value != "")
Because the email field contains text, this rule is evaluated as true and so the rest of the else if blocks won't be executed.
I'd consider changing the else if's to be individual if statements so that they won't stop each other.
You have to remove the return false statements inside if condition. Inside validation function, at the end you have to return false if any of the validation fails. Here's an example to do it:
var result = true;
if(condition 1){ // if condition 1 fails, make result = false;
}
if(condition 1){ // if condition 2 fails, make result = false;
}
if(condition 1){ // if condition 3 fails, make result = false;
}
return result; // After all validations, result result
That's it.
Replace your correction place with this code....
else if(signupEmailAddress[0].value != "" && !(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/).test(signupEmailAddress[0].value)) // problem in this section
{
alert("Please enter a valid email address.");
signupEmailAddress[0].focus();
return false;
}

Categories

Resources