Check if user input has certain characters - javascript

Hi I'm making a "secure password" project for school and I need help to check if a user input has "!#$%&#" and if they have it tell them their password is secure.
This is a project for school Im stuck doing this :(
var password = document.getElementById('password');
var eMsg = document.getElementById('feedback');
var minLength = 6;
function checkPass() {
if (password.value.length < minLength) {
eMsg.innerHTML = 'Password must have' + minLength + 'characters or more';
} else {
eMsg.innerHTML = '';
}
}
<html>
<head>
<title> Password Secured </title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1 class="logo"> logo</h1>
<br/>
<br/>
<p class="input">Please type your password: <br/> <input type="text" id="password" />
<div id="feedback"></div>
</p>
<br/>
<p class="answer"></p>
<br/>
<br/>
<p class="tips"> <br/>Tips tips tips </p>
</body>
</html>

You can test a string using this regular expression:
function isValid(str){
return !/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
}
Possible duplicate of
javascript code to check special characters

Use a regular expression.
// Returns TRUE if the string contains one of these characters.
// Returns FALSE otherwise
/[!#$%&#]/.test(password)

Use the regular Expression
var password = document.getElementById('password');
password.addEventListener('blur',checkPass);
var eMsg = document.getElementById('feedback');
var minLength = 6;
function checkPass () {
if (password.value.length < minLength ) {
eMsg.innerHTML = 'Password must have' + minLength + 'characters or more';
} else if(/[!#$%&#]/.test(password.value)){
eMsg.innerHTML = 'Your password is secure';
}
}
<html>
<head>
<title> Password Secured </title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1 class="logo"> logo</h1>
<br></br>
<br></br>
<p class="input">Please type your password: <br></br> <input type="text" id="password"/> <div id="feedback"></div> </p>
<br></br>
<p class="answer"></p>
<br></br>
<br></br>
<p class="tips"> <br></br>Tips tips tips </p>
</body>

You are looking for a code using a regular expression.
What you should do is the following:
document.getElementById("myInput").value.match(/[\!\\#\$\%\&\#]+/g)
and check if this matched anything, if it does, then you properly matched any of those characters.

Related

How do we apply Bootstrap classes to JavaScript Error messages and make them stay on the screen when a form submit button is clicked?

I am trying to figure out how to make Javascript error messages be displayed in the DOM and stay there until valid information is added into the form inputs. Right now they appear for a brief moment and then disappear. On top of that, I have to use Bootstrap 5 to stylize the JavaScript Error messages. I've been trying to figure this out all day and I haven't had any luck.
I have my HTML and Javascript down below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Login Form</title>
<link rel="stylesheet" href="login/login.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
</head>
<body>
<main>
<h1 class="text-primary">Login</h1>
<form id="login_form" name="login_form" method="get">
<div>
<label for="email1">Email:</label>
<input name="email" type="email" autocomplete="email" id="email" class="form-control">
<span class="text-danger">*</span>
<span id="errorName"></span>
</div>
<div>
<label for="password">Password:</label>
<input name="password" type="password" autocomplete="password" id="password" class="form-control">
<span class="text-danger">*</span>
<span id="errorName"></span>
</div>
<div>
<label> </label>
<button type="submit" class="btn btn-primary" id="login">Login
</div>
</form>
</main>
</main>
<script defer src="login/login.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
</body>
</html>
const $ = selector => document.querySelector(selector);
document.addEventListener("DOMContentLoaded", () => {
$("#login").addEventListener("click", () => {
// get values user entered in textboxes
const email = $("#email");
const password = $("#password");
// create a Boolean variable to keep track of invalid entries
let isValid = true;
// check user entries - add text to error message if invalid
if (email.value == "" || password.value == "") {
email.nextElementSibling.textContent = "You seem to have forgotten your username and password.";
password.nextElementSibling.textContent = "You seem to have forgotten your username and password.";
return false;
} else {
email.nextElementSibling.textContent = "";
password.nextElementSibling.textContent = "";
}
if (email.value == "admin#example.com" && password.value == "password") {
document.writeln("Welcome back Admin!")
} else {
document.writeln("That email and password doesn't seem to be right. Try again.")
}
// submit the form if all entries are valid
if (isValid) {
$("#login_form").submit();
}
});
});

if statement passed but else statement is also executed - JavaScript

I have a login system that loops through an array of objects to fetch and compare username and password entered by the user in the login page. I have issued an if statement to check if user credentials are correct. The problem am having is that the system shows the else statement even when the if statement has passed or the user credentials are correct.
Please see the full demo in the link below;
https://jsfiddle.net/dej5sr9z/
Here is my HTML code
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE" />
<meta name="generator" content="Ayub Technologies">
<meta name="author" content="Verai Bosobori" />
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
<meta name="description" content="">
<title>Lycan CREATIONS | Home</title>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<section>
<div class="form_div">
<h2>Login</h2>
<div style="text-align:left; color:red; font-weight:bold;" id="error"></div>
<div style="text-align:left; color:green; font-weight:bold;" id="success"></div>
<br>
<form action="#">
<div class="form_input">
<label for="">Username</label>
<input type="text" id="username" placeholder="">
</div> <br>
<div class="form_input">
<label for="">Password</label>
<input type="password" id="passwd" placeholder="">
</div>
<div class="form_input">
<p style="text-align:left; color:blue;">Forgot Password?</p>
</div>
<div class="form_submit">
<button type="submit" onclick="getInfo()">Submit</button>
</div>
</form>
</div>
</section>
</body>
</html>
Beolow is the JavaCript Code
var objPeople =[
{
username: "verai",
passwd: "lycan"
},
{
username: "ayub",
passwd: "metah"
},
{
username: "chris",
passwd: "forever"
}
]
function getInfo(){
var username = document.getElementById("username").value;
var passwd = document.getElementById("passwd").value;
var error = document.getElementById("error").innerHTML;
if (username != '' || passwd != ''){
for(i = 0; i < objPeople.length; i++){
if(username == objPeople[i].username && passwd == objPeople[i].passwd){
document.getElementById("success").innerHTML = "Hello " + username + "!! You are successfully logged in!!!";
console.log(username + " is logged in!!!");
setTimeout(function(){
document.getElementById("success").innerHTML = "";
document.getElementById("username").value = "";
document.getElementById("passwd").value = "";
},5000);
}else{
document.getElementById("error").innerHTML = " Incorrect Username or Password. Please try again!";
setTimeout(function(){
document.getElementById("error").innerHTML = "";
document.getElementById("username").value = "";
document.getElementById("passwd").value = "";
},2000);
}
}
}else{
// console.log("Your username is " + username + " and your password is " + passwd );
document.getElementById("error").innerHTML = "All fields required, please try again!";
setTimeout(function(){
document.getElementById("error").innerHTML = "";
document.getElementById("username").value = "";
document.getElementById("passwd").value = "";
},2000);
}
}
I will appreciate if someone points out what am not doing right, thanks.
Assuming a correct combination has been entered, the for-loop goes into the if-part once for the matching user, but also it goes into the else-part for all other non-matching users. There is nothing in place to prevent that from happening.
You need to determine who is the one matching person if any, and then proceed with that result (which is either a user object, or undefined).
You can do so with find, using code like this:
var matchingUser = objPeople.find(p => username === p.username && passwd === p.passwd);
if (matchingUser) {
// ...
} else {
// ...
}
Side note - I used the "triple equal sign", which does an exact comparison between objects without any type conversions that could get in the way.

Why javascript function don't work for onclick event

I am trying to execute a event to verify if 2 input values are equals, but the javascript function dont works
I want to compare the valus of 2 text input box in realtime, like webforms, when the user type into the text box, the web says if the values match or not
This is the HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h2 id="resultado">Resultado</h2>
<div >
<label id="passwordlabel" for="password1">Contraseña</label>
<input name="password" type="text" id="password" placeholder="Contraseña" required>
<div class="invalid-feedback">
Contraseña no válida.
</div>
</div>
<div >
<label for="password2">Confirme Contraseña</label>
<input name="password2" type="password" id="password2" onclick="pass()" placeholder="Repita contraseña" required>
<div class="invalid-feedback">
Las contraseñas deben ser iguales.
</div>
</div>
<script src="js/password-validation.js"></script>
</body>
</html>
And this is the JS file
function pass() {
'use strict'
result=document.getElementById("resultado");
result.innerHTML = "el java script sirve";
var inputPassword = document.getElementById('password').value;
var inputPassword2 = document.getElementById('password2').value;
if ( inputPassword != inputPassword2) {
result.innerHTML = "values don't match";
}
else{
result.innerHTML = "values match";
}
})
Thank you
1- At the end of your function you have an unnecessary parentheses )
2- If you use use strict you need to declare your variables: var result = ...
3- Probably is conceptually wrong to check the two fields with an onclick on textbox, but this is not a formal error.
function pass() {
'use strict'
var result = document.getElementById("resultado");
result.innerHTML = "el java script sirve";
var inputPassword = document.getElementById('password').value;
var inputPassword2 = document.getElementById('password2').value;
if (inputPassword != inputPassword2) {
result.innerHTML = "values don't match";
} else {
result.innerHTML = "values match";
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h2 id="resultado">Resultado</h2>
<div >
<label id="passwordlabel" for="password1">Contraseña</label>
<input name="password" type="text" id="password" placeholder="Contraseña" required>
<div class="invalid-feedback">
Contraseña no válida.
</div>
</div>
<div >
<label for="password2">Confirme Contraseña</label>
<input name="password2" type="password" id="password2" onclick="pass()" placeholder="Repita contraseña" required>
<div class="invalid-feedback">
Las contraseñas deben ser iguales.
</div>
</div>
<script src="js/password-validation.js"></script>
</body>
</html>

Uncaught TypeError: Cannot set property 'innerHTML'

I'm sorry if this is a repeat post, I haven't been able to locate anything covering my particular problem. So I'm using Javascript to validate a form to check for empty fields, and I'm using method="get" to push the data to another html page. On that page the data is interpretted from the query string and displayed. This is for a class and I keep getting "Uncaught TypeError: Cannot set property 'innerHTML' of null". I have provided all of my code below. I would really appreciate any help figuring out what is happening. Cheers.
The errors I am receiving..
<--Form Submit.htm-->
<!DOCTYPE html>
<html>
<head>
<title>jpratt_Lab04-Form Validation</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script>
// Function gets data submitted on first page and displays it on the second page
function getData() {
// Set formData to the query string passed in by the page URL
var formData = location.search;
// Extract the characters from formData where 0 is the first character
formData = formData.substring(1, formData.length);
// Replace all characters in formData as "+" => " " AND "=" => ": " AND "%40" => "#"
while (formData.indexOf("+") != -1 || formData.indexOf("=") != -1) {
formData = formData.replace("+", " ");
formData = formData.replace("=", ": ");
// Firefox and Chrome use %40 for the "#" char in email address
formData = formData.replace("%40", "#");
}
// Split the string formData into an array, "&" is the delimiter used to split string
var interestList = "Interests: ";
var formArray = formData.split("&");
// Write array values to id's on the second page
document.getElementById("user").innerHTML = formArray[0];
document.getElementById("email").innerHTML = formArray[1];
document.getElementById("password").innerHTML = formArray[2];
document.getElementById("passwordConfirm").innerHTML = formArray[3];
document.getElementById("specialOffers").innerHTML = formArray[4];
// Create a string “interestList” of reported interests
for (var i = 5; i < formArray.length; i++) {
interestList += formArray[i].substring(11) + ", ";
}
document.getElementById("interests").innerHTML = interestList;
}
</script>
</head>
<body>
<header>
<h1>Website Registration Form</h1>
</header>
<article>
<h2>Your Submitted Information:</h2>
<p id="user"><script>getData();</script></p>
<p id="email"><script>getData();</script></p>
<p id="password"><script>getData();</script></p>
<p id="passwordConfirm"><script>getData();</script></p>
<p id="specialOffers"><script>getData();</script></p>
<p id="interests"><script>getData();</script></p>
</article>
</body>
</html>
<--index.htm-->
<!DOCTYPE html>
<html>
<head>
<title>jpratt_Lab04-Form Validation</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script>
function validate() {
var user = document.forms['form']['user'].value;
var email = document.forms['form']['email'].value;
var pass = document.forms['form']['pass'].value;
var confirmPass = document.forms['form']['confirmPass'].value;
var specialOffers = document.forms['form']['specialOffers'].value;
var errors = false;
var userError = document.getElementById('userWarning');
var emailError = document.getElementById('emailWarning');
var passError = document.getElementById('passWarning');
var soError = document.getElementById('soError');
try {
if (user == '' || user == 'Please enter your name..') throw userError.innerHTML = 'Your name is required.';
}
catch (err) {
var errors = true;
err;
}
try {
if (email == '' || email == 'Please enter your email..') throw emailError.innerHTML = 'Your email is required.';
}
catch (err) {
var errors = true;
err;
}
try {
if (pass == '' || confirmPass == '') throw passError.innerHTML = 'Password is required.';
if (pass != confirmPass) throw passError.innerHTML = 'Passwords do not match.';
}
catch (err) {
var errors = true;
err;
}
try {
if (specialOffers == '') throw soError.innerHTML = 'You must select yes or no.';
}
catch (err) {
var errors = true;
err;
}
// var chkd = document.getElementByID['form']['interests'].value;
// alert(chkd);
if (errors == true) {
return false;
}
else {
}
}
</script>
</head>
<body>
<header>
<h1>Website Registration Form</h1>
</header>
<article>
<form name="form" method="get" enctype="application/x-www-form-urlencoded" action="form-submit.htm" onsubmit="return validate()">
<h2>Personal Information:</h2>
<p>
<label name="user">Name:</label>
<input type="text" name="name" id="user" value="Please enter your name.." />
</p>
<p id="userWarning" class="alert"></p>
<p>
<label name="email">Email:</label>
<input type="text" name="email" id="email" value="Please enter your email.." />
</p>
<p id="emailWarning" class="alert"></p>
<h2>Security Information:</h2>
<p>
<label name="pass">Password:</label>
<input type="password" name="pass" id="pass" />
</p>
<p>
<label name="confirmPass">Confirm Password:</label>
<input type="password" name="confirmPass" id="confirmPass" />
</p>
<p id="passWarning" class="alert"></p>
<h2>Security Information:</h2>
<p class="alignleft">
<label name="specialOffers">E-mail Specail Offers:</label>
<input type="radio" name="specialOffers" id="specialOffers" value="true" />Yes
<input type="radio" name="specialOffers" id="specialOffers" value="false" />No
</p>
<p id="soError" class="alert"></p>
<p class="alignleft">
<label name="interests">Interests:</label><br>
<input type="checkbox" name="interests" id="entertaiment" value="entertainment" />Entertainment<br>
<input type="checkbox" name="interests" id="interests" value="business" />Business<br>
<input type="checkbox" name="interests" id="interests" value="music" />Music<br>
<input type="checkbox" name="interests" id="interests" value="shopping" />Shopping<br>
<input type="checkbox" name="interests" id="interests" value="travel" />Travel
</p>
<p id="interestError" class="alert"></p>
<p class="buttons">
<input type="submit" />
<input type="reset" value="Reset"/>
</p>
</form>
</article>
<footer></footer>
</body>
</html>
Your problem is down here:
<p id="user"><script>getData();</script></p>
<p id="email"><script>getData();</script></p>
<p id="password"><script>getData();</script></p>
<p id="passwordConfirm"><script>getData();</script></p>
<p id="specialOffers"><script>getData();</script></p>
<p id="interests"><script>getData();</script></p>
You are calling the function getData() for 6 times and you need to call it only once since in the function you have already this:
// Write array values to id's on the second page
document.getElementById("user").innerHTML = formArray[0];
document.getElementById("email").innerHTML = formArray[1];
document.getElementById("password").innerHTML = formArray[2];
document.getElementById("passwordConfirm").innerHTML = formArray[3];
document.getElementById("specialOffers").innerHTML = formArray[4];
The DOM parses from top-down so the browser reads your #user paragraph then it stops to launch the getData() function. Your function gets to execute document.getElementById("user") and all it's fine, then it goes next to execute document.getElementById("email") and it throws an error simply because your browser is still stuck at the #user paragraph and it didn't parsed the #email paragraph yet.
The solution to this is to remove <script>getData();</script> from all the tags and then place a single call at the end of your HTML document, just before the closing body tag.
In a nutshell this is one of the main reasons why libraries are generally loaded on the head tag while all the custom code, including DOM manipulation is usually loaded at last.

JavaScript not executing with form validation

I am relatively new to web development and I'm trying to do some form validation with javascript but my javascript block is not executing and I really don't know why. Any ideas?
<html>
<head>
<title>Login</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link type = "text/css" rel = "stylesheet" href = "formato.css" />
<script type = "text/javascript">
function validate(){
var x = document.forms[LoginInformation][username].value;
var y = document.forms[LoginInformation][password].value;
if(document.LoginInformation){
alert("Enter a username");
return false;
}
if(y===null || x ===""){
alert("Enter a password");
return false;
}
}
</script>
</head>
<body>
<center>
<div id = "login">
<form method = "post" name = "LoginInformation" onsubmit = "return (validate());" action="./TestLogin">
<fieldset>
<legend>Información de Login</legend>
<label>Usuario:<br />
<input type="text" name="username" size ="15"/></label><br />
<label>Contraseña:<br />
<input type="password" name="password" size ="15"/></label><br />
<label><br /><input type = "submit" name = "login" value = "Login"/></label><br />
</fieldset>
</form>
</div>
</center>
</body>
Please pass the form id and control id as string as mentioned below
var x = document.forms["LoginInformation"]["username"].value;
var y = document.forms["LoginInformation"]["password"].value;
Try this:
<script type = "text/javascript">
function validate(){
var x = document.getElementbyID("username");
var y = document.getElementbyID("password");
if(x==""){
alert("Enter a username");
return false;
}
if(y==null || x ==""){
alert("Enter a password");
return false;
}
}
</script>
and then all you code in between
<form method="post" name="LoginInformation" action="./TestLogin">
<fieldset>
<legend>Información de Login</legend>
<label>Usuario:<br />
<input type="text" id="username" size ="15"/></label><br />
<label>Contraseña:<br />
<input type="password" id="password" size ="15"/></label><br />
<label><br /><input type ="submit" name ="login" value = "Login" onClick="validate()"/></label><br />
</fieldset>
</form>
in your validate function you need to have LoginInformation, username, and password enclosed in quotation marks. If it's not, your JavaScript interpreter will consider them as regular ol' JavaScript variables, which they're not.

Categories