User Validation in Java Script using Static Password - javascript

I am new to Java Script and recently got a program in JS For Implementing Static Password Protection
Here is my code :
<html>
<head>
<title>
User Validation : 2nd Program
</title>
<script "javascript">
function validate()
{
alert(form.username.value)
alert(document.getelementbyId(username).value);
alert(form.password.value)
if(form.username.value == "sample" && form.password.value =="password")
{
alert("User Validated ");
continue();
}
else
{
alert("Incorrect Username or Password" );
}
}
</script>
</head>
<body>
<text align=center>
<form name="form" onsubmit="validate()">
Username <input type="text" name="username" />
<br />
<br />
Password <input type="password" name="password" maxlength=10 />
<input type="submit" />
</form>
</text>
</body>
Now , I have defined a username->"sample" by default and password ->"password" by default for user validation .
But whenever after submitting the form resets again without executing the validate function !
As am new to JS ignore me for a silly mistake .
Also suggest some best books for Learning JS and JSP from the scratch !

change onsubmit="validate()" to onsubmit="return validate();".
this way, when validate returns false, the form won't submit. you'd also have to change the validate func to return false when the form doesn't validate, the resulting code would be:
function validate()
{
alert(form.username.value)
alert(document.getelementbyId(username).value);
alert(form.password.value)
if(form.username.value == "sample" && form.password.value =="password")
{
alert("User Validated ");
return true;
}
else
{
alert("Incorrect Username or Password" );
return false;
}
}
Update: continue and break illustrated.
while(true) {
// :loopStart
var randomNumber = Math.random();
if (randomNumber < .5) {
continue; //skips the rest of the code and goes back to :loopStart
}
if (randomNumber >= .6) {
break; //exits the while loop (resumes execution at :loopEnd)
}
alert('value is between .5 and .6');
}
// :loopEnd
just in case, :loopStart and :loopEnd aren't special identifiers or anything, they're just comments to help you trace the code better

Related

Having error in sign up and sign in for blogging websites

First of all, I'm a beginner so, I don't know much but, I expect you would help me.
I've made a website for blogging where you sign up and it redirects you to the main page. Here it should tell me if I already signed up once.
I should get an alert if I have signed up before and it should check pass but, here I am not getting it like that. In fact, it redirects even if I have entered the wrong password for the username.
I don't know why this happens...
Signup.html :
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href= "blog.css">
<meta charset="UTF-8">
<title>Page title</title>
</head>
<body>
<div class="Title" align="center">
<br>
<hr>
<h1> InFinite Blogging</h1>
<hr>
<br>
</div>
</div>
<form id="form" action="signup.html" method="post">
<div class="signup">
<input type="text" id="username" placeholder="username">
<br>
<input type="password" id="password" placeholder="password" >
<button id="next" onclick="check()">sign up </button>
</div>
</form>
<script src="blog.js"></script>
</body>
</html>
Blog.js :
var avail = false;
localStorage.setItem(0, 'admin');
localStorage.setItem('admin', '12345678');
function check() {
var user = document.getElementById('username').value;
var pass = document.getElementById('password').value;
var max1 = Object.keys.length;
var max = Object.keys.length-1;
if( user == "" || user== null || pass ==""|| pass==null ) {
alert("enter your name and password, first.");
document.getElementById('username').focus;
document.getElementById('password').focus;
return false;
} else if(pass.length<8) {
alert("Password must contain 8 characters.");
document.getElementById('username').focus;
document.getElementById('password').focus;
return false;
} else {
for (i = 0; i <= max; i++) {
if (user == localStorage.getItem(i)) {
alert("it looks like you already have account 😃.");
avail=true;
PASS = localStorage.getItem(user);
if (pass!=PASS) {
alert("Please, check your password and write correctly.");
} else if(pass==PASS) {
avail='correct';
}
}
}
if(avail!=true) {
localStorage.setItem(max1, user)
localStorage.setItem(user, pass)
document.getElementById("form").action = 'main.html';
} else if(avail=='correct') {
document.getElementById("form").action = 'main.html';
}
}
}
if(avail == false){
localStorage.setItem(max1, user)
localStorage.setItem(user, pass)
document.getElementById("form").action = 'main.html';}
or
else if(pass==PASS) {
confirmed='correct';
}
There are 2 possible solutions:
check for if(avail == false)
use another variable when the password has been confirmed.
By redeclaring avail = "correct", you are changing the typeof(avail) from boolean to string. Avail will never be true because it's no longer a boolean.

How do I check if input is blank/not blank and do specific thing

Okay so I know this is probably a headache for most of you but i'm having trouble figuring this out as javascript is not my strong suit.
I'm trying to basically get this one page to load if username and password is not blank but if it is blank I want it to alert to me (specifically window.alert()) that I have not inputted username and/or password.
I cannot seem to figure it out so here it is.
<button type="submit" id="enterButton" onclick="newPage()"><strong>Enter</strong></button>
there is my button where I put my function on
var username = getElementById("userName");
var password = getElementById("passWord");
function newPage() {
if(username.val().length==0 || password.val().length==0){
alert("please enter valid information");
return location.href = "newPage.html";
}
else{
location.href = "newPage.html";
}
}
and here is my failed attempt to initialize my idea.
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;
if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if (password==null || password==""){
alert("password can't be blank");
return false;
} else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
<html>
<body>
<body>
<form name="myform" method="post" action="http://www.javatpoint.com/javascriptpages/valid.jsp" onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
</body>
</html>
Try to check first if you can get the value of your username. If you're using plain javascript, you should use document.getElementById("userName").value.

Uncaught ReferenceError: form is not defined

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;
}

How come my JavaScript isn't working?

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.

Onclick event; If and Else

All right so I am doing a javascript code for a login type form and it will lead you to a new page. Here it is:
function submit1()
{
var x=document.getElementById("username");
var y=document.getElementById("password");
if (x.value=="username" && y.value=="password")
{
window.location="Example.php";
}
else
{
window.alert=("The information you have submitted is incorrect and needs to be submitted again!");
}
}
When ever I am hitting the submit button it takes me straight to the page instead of checking to see if it right. Please help!
Thank you in advanced! To let you know this is not a permanet login page!
The easy way to do this would be to use a button input:
<input type="button" value="Check" onclick = "submit1();" />
The alternative is to prevent this default behavior of a submit type input, by making the handler return false. Your HTML would look like this:
<input type="submit" value="Check" onclick = "return submit1();" />
Your function would need to be changed a well (considering the fact that you want it to not redirect). I am assuming you want to preserve data entered, so I am not going to use window.location to redirect. Instead, I am going to allow the form to be submitted:
function submit1()
{
var x=document.getElementById("username");
var y=document.getElementById("password");
if (x.value == "username" && y.value == "password") {
window.alert=("The information you have submitted is incorrect and needs to be submitted again!");
return false;
}
}
<html>
<head>
<title>
Login page
</title>
</head>
<body>
<h1 style="font-family:Comic Sans Ms;text-align="center";font-size:20pt;
color:#00FF00;>
Simple Login Page
</h1>
<form name="login">
Username<input type="text" name="userid"/>
Password<input type="password" name="pswrd"/>
<input type="button" onclick="check(this.form)" value="Login"/>
<input type="reset" value="Cancel"/>
</form>
<script language="javascript">
function check(form)/*function to check userid & password*/
{
/*the following code checkes whether the entered userid and password are matching*/
if(form.userid.value == "myuserid" && form.pswrd.value == "mypswrd")
{
window.location="Example.php"; /*opens the target page while Id & password matches*/
}
else
{
alert("Error Password or Username")/*displays error message*/
}
}
</script>
</body>
</html>
The event needs to cancel the default event and return false. This will prevent the form from submitting.
HOWEVER, it should be a non-issue if the form submits anyway, because JavaScript CANNOT be trusted and therefore you MUST validate all input server-side.
<form method="post" action="." id="myform">
<!-- form contents --->
</form>
<script type="text/javascript">
(function () {
var f = document.getElementById('myform'), // get your form element
x = document.getElementById('username'),
y = document.getElementById('password'),
handler;
handler = function (e) {
e.preventDefault(); // stop submit
if (x.value=='username' && y.value=='password') {
window.location = 'Example.php';
} else {
window.alert('The information...');
}
};
// listen to submit event
if ('addEventListener' in f) {
f.addEventListener('submit', handler, false);
} else { // handle also IE...
f.attachEvent('submit', function () {
handler(window.event);
});
}
}());
</script>
anyway it looks like you're trying to check login/password from JS what is not greatest idea (anyone can just look into source and read it)

Categories

Resources