HTML form being reloaded and java script message not being displayed - javascript

I am a new to Javascript programming. I have developed the below script and encountering the below issues. Request the expert to help to resolve the issues.
Issues are
when both username and password are filled (username not equal to password) the javascript message displays and the form automatically reloads removing the message.
when username or password is left empty, the message being displayed is "Invalid username or password". The correct javascript message is not being displayed.
when both the fields are not filled the script executes successfully and "Welcome" is printed. If condition in javascript not being executed to display the correct message. Also have used "required" attribute to display the error "this field is required" but still "welcome' is being printed.
<!DOCTYPE html>
<html>
<head>
<script>
function verify() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if ((typeof username) == undefined) {
document.getElementById("message").innerHTML = "Username Required.";
}
if ((typeof password) == undefined) {
document.getElementById("message").innerHTML = "password Required.";
}
if (username == password) {
document.write("Welcome");
}
else {
document.getElementById("message").innerHTML = "Invalid Username or password";
}
}
</script>
</head>
<body>
<h1 style="text-align:center">Welcome to MEPC World!!</h1>
<br>
<form style="margin:auto;max-width:60%" >
<fieldset style="border:groove;border-width:5px;border-color:lightgrey;text-align:center">
<legend><b>Login</b></legend>
<p id="message" style="color:red;text-align:left"></p>
<br>
Username :
<input id="username" type="text" placeholder="username (e.g. XYZ)" autocomplete="off" required="required"> </input>
<br>
<br>
Password :
<input id="password" type="password" placeholder="password" required="required"> </input>
<br><br>
<input type="submit" value="Submit" onclick="verify()">
</fieldset>
</form>
<p><b>Note:</b> Username and password are case-sensitive.</p>
</body>
</html>

This is how you should be doing it. Or the message gets overridden because you have multiple if statements instead of an if/elseif/else which will only allow one to be true.
function verify() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username === undefined || username === '') {
document.getElementById("message").innerHTML = "Username Required.";
}
else if (password == undefined || password === '') {
document.getElementById("message").innerHTML = "password Required.";
}
// This doesn't make sense at all fyi
else if (username === password) {
document.write("Welcome");
}
else {
document.getElementById("message").innerHTML = "Invalid Username or password";
}
}
To prevent the form from submitting you have to do this:
<input type="submit" value="Submit" onclick="return verify()">

Related

passoword validation without jQuery

I am making a password validation using js and html. It suppose to show certain information under the input parts if the input is not valid. But whatever the input is, there's no message at all. I am not sure which part I did wrong. Code is posted below
var name = document.getElementById("userName");
var passWord = document.getElementById("passWord");
var flag;
function check() {
flag = validateInput(name, passWord);
if (flag)
isPaswordValid(passWord);
if (flag)
ispassWordStrong(passWord);
}
function validateInput(name, passWord) {
if (name.length = 0 || passWord.length < 0) {
document.getElementById("errorMessage").innerHTML = "Please enter Username and passWord";
return false;
}
else {
document.getElementById("errorMessage").innerHTML = "Valid input";
return true;
}
}
//Check Username and passWord are valid
function isPaswordValid(passWord) {
var re = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/;
//Check passWord is valid or not and having length of passord should not less than 8
if (passWord.length < 8 || (!re.test(passWord))) {
document.getElementById("errorMessage").innerHTML = "Invalid passWord. Please enter new passWord";
return false;
}
else {
document.getElementById("errorMessage").innerHTML = "Valid input";
return true;
}
}
//Check password has no more than 3 characters from username in passWord
function ispassWordStrong(userName, passWord) {
var n = 0;
for (var i = 0; i < userName.length; i++) {
if (passWord.indexOf(userName[i]) >= 0) {
n += 1;
}
}
if (n > 3) {
document.getElementById("errorMessage").innerHTML = "passWord can't contain more than 3 characters from the username.";
}
else {
document.getElementById("errorMessage").innerHTML = "Valid input";
}
}
});
<body>
<fieldset>
<legend>Password Validator</legend>
User Name:
<input type="text" id="userName" name="userName" placeholder="User Name" onkeyup='check();' /><br>
passWord:
<input type="password" id="passWord" name="passWord" placeholder="Password" onkeyup='check();' />
<input type="submit" id="inputValidate" value="Validate"><br /><br />
<b><span style="color:red;" id="errorMessage"></span></b>
</fieldset>
</body>
Sorry for the long codes and thanks for your help.
The following should do what you require:
// collect all DOM elements in object ti: ti.i, ti.e, ti.u, ti.p
const ti=["inputValidate","errorMessage","userName","passWord"]
.reduce((a,c)=>(a[c.substr(0,1)]=document.querySelector('#'+c),a),{});
// delegated event listening for event "input":
document.querySelector('fieldset').addEventListener('input',ev=>{
if (Object.values(ti).indexOf(ev.target)>1){ // for userName and passWord do ...
let u=ti.u.value.toLowerCase();
ti.e.textContent= (ti.p.value.length > 2
&& ti.p.value.split('').reduce((a,c)=>a+=u.indexOf(c.toLowerCase())>-1?1:0,0) > 2 )
? "The password contains at least 3 letters from the username!" : "";
}})
// event listening for button click on "validate":
ti.i.addEventListener('click',ev=>!(ti.e.textContent=
(ti.u.value.trim().length ? "" : "User name is empty.") ||
(ti.p.value.match(/(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}/)
? "" : "The password is not complex enough!" )))
<fieldset>
<legend>Password Validator</legend>
User Name:<br/>
<input type="text" id="userName" name="userName" placeholder="User Name"/><br>
passWord:<br/>
<input type="password" id="passWord" name="passWord" placeholder="Password"/>
<input type="submit" id="inputValidate" value="Validate"><br/>
<b><span style="color:red;" id="errorMessage"></span></b>
</fieldset>
While inputting characters in the fields #userName and #passWord it checks for the occurence of user name characters in the password. This is done ignoring upper or lower case. And when clicking on the "validate" button the complexity of the password is checked against the regular expression /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}/. This regular expression demands at least
one upper case chraracter,
one lower case character
one number and
a minimum length of 8.
There is also a rudimentary check on the user name. It must contain at least one non-blank character. The event handler for the click event on the "validate" button returns false whenever an error is detected. This can be used to prevent the submission of the form. However, the form itself was not supplied by OP.

Using HTML WebStorage to have multiple username and passwords

I am using WebStorage to make a simple login system with username/password. (I don't know if this is the best way.)
It is working, but the problem is, it only works with one username and password. How do I make it so that it can store multiple usernames/passwords? Or perhaps I should be using a different system to do this?
Code:
<html>
<head>
</head>
<body>
<input type="text" placeholder="input username here" id="textbox">
<input type="text" placeholder="input password here" id="textbox2">
<input type="button" value="sign up" onclick="signup()">
<br>
<input type="text" placeholder="input username here" id="textbox3">
<input type="text" placeholder="input password here" id="textbox4">
<input type="button" value="login" onclick="login()">
<p id="result"></p>
<br>
<br>
<div id="settings">
<h1>Settings</h1>
<br>
<input type="text" placeholder="background color" id="bgc">
<br>
<input type="button" onclick="changeSettings()" value="Change settings">
</div>
<script>
function changeSettings() {
if(loggedIn == true) {
if(typeof(Storage)!= "undefined") {
var backg = document.getElementById("bgc").value;
if(backg!="") {
localStorage.setItem("backgroundColor", backg);
document.body.style.background = localStorage.getItem("backgroundColor");
} else {
alert("Enter a color.")
}
} else {
alert("No support.")
}
} else {
alert("You must be logged in to do that.")
}
}
function loadSettings() {
if(typeof(Storage)!="undefined") {
document.body.style.background = localStorage.getItem("backgroundColor");
} else {
alert("No support.")
}
}
function signup() {
if(typeof(Storage)!= "undefined") {
var username = document.getElementById("textbox").value;
var password = document.getElementById("textbox2").value;
if(username!="" && password!="") {
localStorage.setItem("username", username);
localStorage.setItem("password", password);
} else {
alert("Please enter a valid username and password.")
}
} else {
alert("No support.")
}
}
function login() {
if(typeof(Storage)!= "undefined") {
var username = localStorage.getItem("username");
var password = localStorage.getItem("password");
var usernameInput = document.getElementById("textbox3").value;
var passwordInput = document.getElementById("textbox4").value;
if(usernameInput!="" && passwordInput!="") {
if(usernameInput == username && passwordInput == password) {
document.getElementById("result").innerHTML = "Logged in!";
loggedIn = true;
loadSettings();
} else {
document.getElementById("result").innerHTML = "Wrong password/username!";
}
} else {
alert("Please enter a valid username and password.")
}
} else {
alert("No support.")
}
}
</script>
</body>
</html>
ps: sorry if it's messy :p
You should probably be using SQL if you want to store user inputs such as Usernames and Passwords.
Hashing & Password Storage
Good video to watch if your trying to learn Databases!
:)
Not a good way to store the plain username/password in localStorage. anyone can change those value. Since you check the login using
localStorage.setItem("username", username);
localStorage.setItem("password", password);
var username = localStorage.getItem("username");
var password = localStorage.getItem("password");
usernameInput == username && passwordInput == password
This login condition can make true using different ways.
Found this article from the Google, Hope you'll get some idea to do in
secure way :)

Remove form error with correct input

I just made a registration form which will tell you in red(CSS) letters if something is wrong. However I want this text to go away as soon as the user writes it correctly. How do I do that?
<script>
function validateForm2() {
var usrnm2 = document.getElementById("usrnm2").value;
var passw2 = document.getElementById("passw2").value;
var cnfpassw2 = document.getElementById("cnfpassw2").value;
var age = document.getElementById("age").value;
if (usrnm2 == null || usrnm2 == "") {
document.getElementById("error1").innerHTML = "You must enter a username";
return false;
}
else if (passw2 == null || passw2 == "") {
document.getElementById("error2").innerHTML = "You must enter a password";
return false;
}
else if (cnfpassw2 !== passw2) {
document.getElementById("error3").innerHTML = "Password does not match";
return false;
}
else if (age < 18) {
document.getElementById("error4").innerHTML = "You are not old enough to enter this site"
return false;
}
else {
alert("Congratulations, you have registered successfully!")
}
}
</script>
<script>
function register2() {
validateForm2()
}
</script>
<form>
Username:
<input id="usrnm2" type="text" name="username"><p id="error1"></p>
Password
<input id="passw2" type="password" name="password"><p id="error2"></p>
Confirm Password
<input id="cnfpassw2" type="password" name="confirmpw2"><p id="error3"></p>
Age
<input id="age" type="number" name="age"><p id="error4"></p><br />
<input id="bttn2" type="button" value="Register!" onclick="register2()"><br />
</form>
Separate the validation conditions into single block if statements, and then include a handler for returning the fields to normal when they are entered correctly:
if (field is entered incorrectly) {
document.getElementById("error").innerHTML = "You must enter correctly";
return false;
}
else {
document.getElementById("error").innerHTML = "";
}
...
alert("Congratulations, you have registered successfully!");
You simply need to place the alert after all of the statements - it will execute as long as none of the conditions fail and thus return.

PHP Code for Email Comparison / Verification

I am trying to create a function to compare two email fields.
As in :
Email : <input type="text" name="email" id="email" value="<?=$email?>"
required>
Confirm email : <input type="text" name="email2" id="email2"
onblur="confirmEmail()" value="<?=$email2?>" required>
Here is the JavaScript code I inserted into my HTML :
<script type="text/javascript">
function confirmEmail() {
var email = document.getElementById("email").value
var email2 = document.getElementById("email2").value
if (email != email2) {
alert('Email Not Matching!'); }
}
</script>
The code works.
Once the user enters the second email address, localhost displays an alert, saying : "Email not matching"
For extra-measure, I inserted the following into the form's properties : onsubmit="return confirmEmail()
So, if the user ignores the first warning, he gets a second warning when he tries to press the SUBMIT button.
Unfortunately, this is where I am stuck. Because : after the second warning, if the user still does not modify the "confirm email" , the SUBMIT button still works The form gets sent.
How can I modify the code, so that : the error message continues to display until the user changes the email2 correctly??
(I tried using the WHILE function, and the DO....WHILE function. They worked............except that, the error-message kept displaying over and over.........and did not allow me to make the required correction to the email field (haha). I had to close the window completely)
First, give your submit button an ID like this:
<input type="submit" value="Submit" id="mySubmit" disabled="disabled">
And in your if block add:
if (email !== email2) {
alert('Not matching')
document.getElementById("mySubmit").disabled = true;
}else{
document.getElementById("mySubmit").disabled = false;
}
What you could do is:
<script type="text/javascript">
var count=0;
function confirmEmail() {
var email = document.getElementById("email").value
var email2 = document.getElementById("email2").value
function chkEmail(){
if (email != email2 && count==0)
{ alert('Email Not Matching!'); count++ }
else if(email!=email2 && count ==1)
//display warning
}
chkEmail();
}
</script>
I would submit the form with JavaScript.
<form>
Email : <input type="text" name="email" id="email" value="<?=$email?>"
required>
Confirm email : <input type="text" name="email2" id="email2"
onblur="confirmEmail()" value="<?=$email2?>" required>
</form>
<button onclick="formSubmit()">Learn More</button>
Your formSubmit() function would simply pull in the values and submit them after the proper check. This way, regardless of what the user enters, it has to go through your verification before it is submitted.
function formSubmit() {
var email = document.getElementById("email").value;
var email2 = document.getElementById("email2").value;
if (email != email2) {
alert('Email Not Matching!');
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","/Your/Path/To/Your/Form-Processing/?email="+email,true);
xmlhttp.send();
}
The function above will go in your script tags. It checks email and email2 against each and then submits email with GET to the processing page the same way your form would. You can also pass other variables the same way by getting them with document.getElementById('#id').value and then send them through the GET method.
try this bro,
<form name="form" method="post" action="">
Email : <input type="text" name="email" id="email" value="<?=$email?>" required>
Confirm email : <input type="text" name="email2" id="email2" value="<?=$email2?>" required>
<input type="submit" value="submit" onsubmit="return confirmEmail();"/>
</form>
and in java script
<script type="text/javascript">
function confirmEmail() {
var email = document.getElementById("email").value;
var email2 = document.getElementById("email2").value;
if (email != email2)
{ alert('Email Not Matching!'); return false; }
else {
return true;
}
}
</script>

Password Validation javascript

I am trying to create a very very basic profile page using Name, Email, Username, and Password. I have to have a password validation code/button.
The home page will be very similar to a common profile page. The user must be able to input the following:
Name field
Email field
User ID field
Password field 3
Validation Password field
The following buttons are required:
Password validation button
Create Profile button
I can put it all together, but the problem I am having is that the javascript console is telling me that there are some errors in the code...
function validate(){
var pass1 = document.getElementById('password');
var pass2 = document.getElementById('Password2');
if (pass1 == pass2)
{
alert("Passwords Match")
}
else
{
alert("Passwords Do Not Match")
}
}
<head>
<script type="text/javascript" src="Profile Page.js"></script>
</head>
<body>
Enter First and Last Name
<input type="text" id="name">
<br>Enter Your Email Address
<input type="text" id="email">
<br>Please Enter a Username
<input type="text" id="username">
<br>Please Enter a Password
<input type="password" id="password">
<br>Enter Your Password Again
<input type="Password" id="password2">
<br>
<button type="button" id="validate" onClick="validate()">Validate Password</button>
<button type="button" id="create" onClick="submit()">Create Profile</button>
</body>
Ok, so I figured out where my errors were, now the alert that I set up for the passwords not matching is coming up, even when the passwords are the same thing. Any suggestions?
Please try it like this:
function validateForm(){
var pass1 = document.getElementsByName("password")[0].value;
var pass2 = document.getElementsByName("password2")[0].value;
if (pass1 === pass2) {
alert("Passwords Match");
} else {
alert("Passwords Do Not Match");
}
}
Enter First and Last Name
<input type = "text" id = "name" /><br/>
Enter Your Email Address
<input type = "text" id = "email" /><br/>
Please Enter a Username
<input type = "text" id = "username" /><br/>
Please Enter a Password
<input type = "password" name = "password" /><br/>
Enter Your Password Again
<input type = "Password" name= "password2" /><br/>
<button type = "button" id = "validate" onclick = "validateForm();">Validate Password</button>
<button type = "button" id = "create" onclick = "submit()">Create Profile</button>
Below is the generic function to validate password by comparing with repeat password, Contains lowercase, Contains uppercase, Contains digit
function validatePassword(password, repeatPassword){
var MinLength = 6;
var MaxLength = 15;
var meetsLengthRequirements:boolean = password.length >= MinLength && repeatPassword.length <= MaxLength;
var hasUpperCasevarter:boolean = false;
var hasLowerCasevarter:boolean = false;
var hasDecimalDigit:boolean = false;
if (meetsLengthRequirements)
{
for (var i = 0, len = password.length; i < len; i++) {
var char = password.charAt(i);
if (!isNaN( +char * 1)){
hasDecimalDigit = true;
}
else{
if (char == char.toUpperCase()) {
hasUpperCasevarter = true;
}
if (char == char.toLowerCase()){
hasLowerCasevarter = true;
}
}
}
}
var isValid = meetsLengthRequirements
&& hasUpperCasevarter
&& hasLowerCasevarter
&& hasDecimalDigit;
return isValid;
}

Categories