Confirmation message for form submission after validations in JavaScript - javascript

I started learning javascript about 2 weeks ago so I'm really new. I've been messing arround with forms and I can't figure out some stuff.
I made a form in HTML and want to validate it in Javascript.
What I've done so far:
if the the fields are empty and the user presses submit a red border will appear arround the field. The border dissapperas if the users writes something in the field.
What I want to do:
if there are no validation errors and the form is submitted I would like for a confirmation message to appear above the form. The message should be hidden initially and it should say something like: "Thank you for contacting us,(and the first name the user entered in the form)"
I also want to print every information from the input fields in the console after submit.
How can I do this using only vanilla Javascript?
function formValidation() {
if (document.myForm.fname.value == "") {
document.getElementById("first-name").style.border = "2px solid red";
return false;
} else {
document.getElementById("first-name").style.border = "";
};
if (document.myForm.lname.value == "") {
document.getElementById("last-name").style.border = "2px solid red";
return false;
} else {
document.getElementById("last-name").style.border = "";
};
var checkMale = document.getElementById("gender-m").checked;
var checkFemale = document.getElementById("gender-f").checked;
if (checkMale == false && checkFemale == false) {
alert("Please select gender");
return false;
};
if (document.myForm.texta.value == "") {
document.getElementById("area").style.border = "2px solid red";
return false;
} else {
document.getElementById("area").style.border = "";
};
return true;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="css/style.css">
<title>My Form</title>
</head>
<body>
<form id="my-form" name="myForm" action="#" onsubmit="event.preventDefault(); formValidation();">
<div id="msg">Thank you for contacting us, </div>
<input type="text" name="fname" id="first-name" placeholder="First Name"> <br>
<input type="text" name="lname" id="last-name" placeholder="Last Name"> <br>
<label for="gender">Gender:</label> <br>
<input type="radio" name="gender" id="gender-m"> Male <br>
<input type="radio" name="gender" id="gender-f"> Female <br>
<textarea name="texta" id="area" cols="30" rows="10"></textarea> <br>
<button type="submit">Submit</button>
</form>
<script src="index.js"></script>
</body>
</html>

You can do it like this :
function formValidation() {
if (document.myForm.fname.value == "") {
document.getElementById("first-name").style.border = "2px solid red";
return false;
} else {
document.getElementById("first-name").style.border = "";
};
if (document.myForm.lname.value == "") {
document.getElementById("last-name").style.border = "2px solid red";
return false;
} else {
document.getElementById("last-name").style.border = "";
};
var checkMale = document.getElementById("gender-m").checked;
var checkFemale = document.getElementById("gender-f").checked;
if (checkMale == false && checkFemale == false) {
alert("Please select gender");
return false;
};
if (document.myForm.texta.value == "") {
document.getElementById("area").style.border = "2px solid red";
return false;
} else {
document.getElementById("area").style.border = "";
};
var success = true;
if(success){
var data = document.getElementById("first-name").value+','+document.getElementById("last-name").value;
console.log(data);
var html = '';
html +='Thank you for contacting us,'+document.getElementById("first-name").value;
document.getElementById("msg").innerHTML = html;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="css/style.css">
<title>My Form</title>
</head>
<body>
<form id="my-form" name="myForm" action="#" onsubmit="event.preventDefault(); formValidation();">
<div id="msg"></div>
<input type="text" name="fname" id="first-name" placeholder="First Name"> <br>
<input type="text" name="lname" id="last-name" placeholder="Last Name"> <br>
<label for="gender">Gender:</label> <br>
<input type="radio" name="gender" id="gender-m"> Male <br>
<input type="radio" name="gender" id="gender-f"> Female <br>
<textarea name="texta" id="area" cols="30" rows="10"></textarea> <br>
<button type="submit">Submit</button>
</form>
<script src="index.js"></script>
</body>
</html>
When everything in the formValidation() function is validated then the code will set a flag success = true. If the value of success is true we can set a form submission successful message.

Related

Trying to import one js file to another

I managed to import a function from my main.js to my signin.js, but for some reason, I get this error on my sign in html page Cannot read properties of null (reading 'addEventListener')
and the function for the signin js is not working and I need to import the function of the main.js as the signin js function relys on the main.js function to work.
HTML 1 - signin js
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="../js/main.js" type="module"></script>
<script src="../js/signin.js" type="module"></script>
<title>Sign in</title>
</head>
<body>
<main>
<form class="form-container">
<input class="email" type="text" placeholder ="Email Address">
<input class="password" type="password" placeholder ="Password">
Sign In
Register
</form>
</main>
</body>
signin.js imported function
//import function
import { validate } from "../js/main.js";
let registration = validate();
let signInbtn = document.querySelector(".sign-in");
signInbtn.addEventListener("click", check);
function check(){
let storedEmail = localStorage.getItem('email');
let storedPw = localStorage.getItem("password");
let email = document.querySelector(".email");
let password = document.querySelector(".password");
if(email.value == storedEmail && password.value == storedPw){
alert("You are logged in")
}
else{
alert("Email or Password is incorrect please check and try again.")
}
}
}
HTML 2 - main.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="../css/main.css" />
<script src="../js/main.js" type="module"></script>
<title>Register</title>
</head>
<body>
<main>
<div class="heading">
<h1>User Registration</h1>
</div>
<form action="../index.html" class="form-container">
<ul>
<li><label for="name">Name</label>
<input class="name" type="text" name="name" required />
</li>
<li><label for="surname">Surname</label>
<input class="surname" type="text" name="surname" required />
</li>
<li><label for="phone">Phone</label>
<input class="phone" type="text" name="phone" />
</li>
<li><label for="email">Email</label>
<input class="email" type="text" name="email" required /></li>
<li><label for="password">Password</label>
<input class="password" type="text" name="password" required /></li>
<button class="reg">Register</button>
</ul>
</form>
</main>
</body>
</html>
main.js
let registration = document.querySelector(".reg");
registration.addEventListener("click", validate);
export function validate() {
//get html elements
const formEl = {
id: createId(),
name: document.querySelector(".name").value,
surname: document.querySelector(".surname").value,
phone: document.querySelector(".phone").value,
email: document.querySelector(".email").value,
password: document.querySelector(".password").value,
};
let name = formEl.name;
let surname = formEl.surname;
let email = formEl.email;
let password = formEl.password;
if (!name) {
alert("Please fill in name");
}
if (!surname) {
alert("Please fill in Surname");
}
if (!email) {
alert("Please fill in email");
}
if (!password) {
alert("Please create a password");
}
usersArray.push(formEl);
store();
return formEl;
}
This error I get in the HTML 1 page
for some reason, it is preventing the sign-in function from executing. I am doing it this way for practice purposes, I know local storage is not the best method for this, but I am getting used to how local storage works.

Need the output of the inputs to be pushed into the <div>

I'm trying to get the user inputs to be pushed out as a message into a <div> via the button press after confirming that all the inputs are filled and the correct password has been entered. That part works fine but my forEach is not working:
If the user has input a number value lower than 18, I want an if that types out via push "Your name is UName and you are Age years old, you are not of legal age", or else the same result as above but ending with "...you are of legal age".
Any idea how I should go forth?
let nameElement = document.getElementById("UNameInput");
let faultElement = document.getElementById("errorOutput");
let ageElement = document.getElementById("AgeInput");
let clickElement = document.getElementById("button");
let passwordElement = document.getElementById("PasswordInput");
clickElement.addEventListener("click", function(e) {
let feedback = [];
if (UNameInput.value === '' || UNameInput.value === null) {
feedback.push('Name input missing')
}
if (AgeInput.value === '' || AgeInput.value === null) {
feedback.push('Age input missing')
} else if (PasswordInput.value !== 'IHM') {
feedback.push('Password is not valid')
} else {
feedback.forEach((item, i) => {
if (item.AgeInput < 18) {
feedback.push("You are not of not legal age")
} else {
feedback.push(" You are of legal age ")
}
});
}
if (feedback.length > 0) {
e.preventDefault()
faultElement.innerText = feedback.join(", ")
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="JSny.js" defer></script>
</head>
<body>
<div id="errorOutput"></div>
<p id="output"></p>
<div>
<label for="UNameInput">Name Input</label>
<input id="UNameInput" name="name" type="text">
</div>
<div>
<label for="AgeInput">Age Input</label>
<input id="AgeInput" name="age" type="number">
</div>
<div>
<label for="PasswordInput">Password Input</label>
<input id="PasswordInput" name="password" type="password">
</div>
<button id="button">Submit</button>
</body>
</html>
You are using AgeInput instead of ageElement in the if statement.

Cannot set property 'innerHTML' of null at validation at HTMLInputElement.onkeydown

I was making simple contact form with email validation, but I ran into an error in my JS code. I was trying to figure out how to fix it but I have no idea what to do.
I was also trying different solutions from other People on StackOverflow but nothing work.
This Is My HTML code :
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../assets/css/style.css">
<title>blackbubble | Contact</title>
</head>
<body>
<form action="#" id="form">
<div class="form_body">
<div class="form_title">
<span></span>
<h1>Get In Touch</h1>
<span></span>
</div>
<div class="user_name">
<input type="name" placeholder="Your name"></input>
<input type="name" placeholder="Second name">
</div>
<div class="email">
<input type="email" id="email" placeholder="Your email address" onkeydown="validation()">
<p class="text"></p>
</div>
<div class="textarea_box">
<textarea placeholder="Message"></textarea>
</div>
<div class="form_footer">
<button class="btn btn_submit">Submit</button>
</div>
</div>
</form>
<script src="../assets/js/main.js"></script>
</body>
</html>
here is my JS Code:
function validation() {
var form = document.getElementById("form");
var email = document.getElementById("email").value;
var text = document.getElementById("text");
var text = document.getElementById("text");
var pattern = /^[^ ]+#[^ ]+\.[a-z]{2,3}$/;
if (email.match(pattern)) {
form.classList.add("valid");
form.classList.remove("invalid");
text.innerHTML = "Your Email Address Is Valid.";
text.style.color = "#00ff00";
}
else {
form.classList.remove("valid");
form.classList.add("invalid");
text.innerHTML = "Please Enter A Valid Email Address.";
text.style.color = "#ff0000";
}
}
There is no element with the id text.
You probably meant to select the element with the class text instead. This can be done with document.querySelector() and the .text CSS selector.
function validation() {
var form = document.getElementById("form");
var email = document.getElementById("email").value;
var text = document.querySelector(".text");
var pattern = /^[^ ]+#[^ ]+\.[a-z]{2,3}$/;
if (email.match(pattern)) {
form.classList.add("valid");
form.classList.remove("invalid");
text.innerHTML = "Your Email Address Is Valid.";
text.style.color = "#00ff00";
} else {
form.classList.remove("valid");
form.classList.add("invalid");
text.innerHTML = "Please Enter A Valid Email Address.";
text.style.color = "#ff0000";
}
}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../assets/css/style.css">
<title>blackbubble | Contact</title>
</head>
<body>
<form action="#" id="form">
<div class="form_body">
<div class="form_title">
<span></span>
<h1>Get In Touch</h1>
<span></span>
</div>
<div class="user_name">
<input type="name" placeholder="Your name">
<input type="name" placeholder="Second name">
</div>
<div class="email">
<input type="email" id="email" placeholder="Your email address" onkeydown="validation()">
<p class="text"></p>
</div>
<div class="textarea_box">
<textarea placeholder="Message"></textarea>
</div>
<div class="form_footer">
<button class="btn btn_submit">Submit</button>
</div>
</div>
</form>
</body>
</html>

Java script Validation on an html form in not working?

I coded an HTML form where I tried to validate it using javascript, However, the validation doesn't work. It should work on click of submit button. Everything looks fine! could not find the error! Please Help.
Below is the code for the page:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Term Deposit Interest Calculator</title>
<link rel="stylesheet" href="css/style.css" media="screen" type="text/css" />
<script>
function validateform(){
var amount=document.myform.amount.value;
var years=document.myform.years.value;
var interst= document.myform.interst.value;
if (amount==null || amount==""){
alert("Amount can't be blank");
return false;
}else if (years==null || years==""){
alert("Years can't be blank");
return false;
}else if (interest==null || interest==""){
alert("Interest can't be blank");
return false;
}
}
</script>
</head>
<body>
<div class="card">
<h3>Term Deposit Interest Calculator</h3><br>
<form name = "myform" method="post"onsubmit="return validateform()">
<input type="text" name="amount" placeholder="Deposit Amount"><span id="num1"></span>
<input type="text" name="years" placeholder="Number Of Years"><span id="num2"></span>
<input type="text" name="interest" placeholder="Yearly Interst Rate"><span id="num3"></span>
<input type="submit" name="submit" class="my submit" value="Total Amount">
</form>
<div class="result">
</div>
</div>
</body>
</html>
<?php
if (!isset($amount7032)) { $amount7032 = ''; }
if (!isset($interest7032)) { $interest7032 = ''; }
if (!isset($years7032)) { $years7032 = ''; }
?>
You have written wrong form element name at below line
var interst= document.myform.interst.value;
it should be
var interest= document.myform.interest.value;
Basically because javascript was not able to find the form element and it was failing due to that.
I tried below code and its working:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Term Deposit Interest Calculator</title>
<link rel="stylesheet" href="css/style.css" media="screen" type="text/css" />
<script>
function validateform(){
var amount=document.myform.amount.value;
var years=document.myform.years.value;
var interest= document.myform.interest.value;
if (amount==null || amount==""){
alert("Amount can't be blank");
return false;
}else if (years==null || years==""){
alert("Years can't be blank");
return false;
}else if (interest==null || interest==""){
alert("Interest can't be blank");
return false;
}
}
</script>
</head>
<body>
<div class="card">
<h3>Term Deposit Interest Calculator</h3><br>
<form name="myform" method="post" onsubmit="return validateform()">
<input type="text" name="amount" placeholder="Deposit Amount"><span id="num1"></span>
<input type="text" name="years" placeholder="Number Of Years"><span id="num2"></span>
<input type="text" name="interest" placeholder="Yearly Interst Rate"><span id="num3"></span>
<input type="submit" name="submit" class="my submit" value="Total Amount">
</form>
<div class="result">
</div>
</div>
</body>
</html>

character validation is not working in javaScript

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form>
Name:<input type="text" id="t1" /> <br> Gender: <input
type="radio" name="sex" value="male">male <input type="radio"
name="sex" value="female">female <br> <input
type="submit" value="submit" onclick="myFunction()">
</form>
<script type="text/javascript">
var regexp = /^[a-zA-Z]+$/;
function myFunction() {
var str = document.getElementById("t1").value;
if (str == "") {
alert("plz enter anything");
}
else if (str.value.match(regexp)) {
alert("Letter Validation: Successful.");
} else {
alert("not valid input");
}
}
</script>
</body>
</html>
I want to do character validation.when user input except character it should display invalid input.but It is neither working nor showing any error message.I don't know why it is not working........
Change
else if (str.value.match(regexp)) {
to
else if (str.match(regexp)) {
Because you already have the value of t1 in str variable.

Categories