I am trying to validate a form by seeing if all the inputs are filled. So here when either email or password are empty, it should return an alert. But when I run this html file, it isn't alerting me of that.
My code:
function validateform() {
var name = document.login.email.value;
var password = document.login.password.value;
if (name == null || name == "") {
alert("Name can't be blank");
return false;
} else if (password.length < 6) {
alert("Password must be at least 6 characters long.");
return false;
}
}
<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">
<title>Document</title>
</head>
<body>
<form name="login" onsubmit="return validateform()" method="post" action="/login_process">
<label for="email">BCBS outlook email</label>
<br>
<input type="email" name="email" id="email" text="BCBS outlook email">
<br>
<label for="pass">Password</label>
<br>
<input type="password" name="pass" id="pass">
<br>
<input type="button" value="submit">
</form>
</body>
</html>
Thanks in advance.
<script type="text/javascript">
function validateform(){
var name = document.getElementById("email").value;
var password = document.getElementById("pass").value;
if (name.replace(/\s/g, '') === ""){
alert("Name can't be blank");
return false:
}
if (password.replace(/\s/g, '').length < 6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
You should access the value of DOM elements by DOM Methods like document.getElementById(), document.querySelector(), document.getElementsByClassName(), document.querySelectorAll() etc.
You can do the validation in two ways:
With Pure HTML
With JavaScript
1) With Pure HTML
By adding required attribute to email and password fields browser will do the validation.
<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">
<title>Document</title>
</head>
<body>
<form name="login" onsubmit="return validateform()" method="post" action="/login_process">
<label for="email">BCBS outlook email</label>
<br>
<input type="email" name="email" text="BCBS outlook email" required>
<br>
<label for="pass">Password</label>
<br>
<input type="password" name="pass" required>
<br>
<input type="submit" value="submit">
</form>
</body>
</html>
2. With JavaScript
Even if browser can validate the form fields by default, using javascript is considered as best practice for validation.
In snippet below .trim() is used to remove whitespace from the strings in form fields.
Guard Clause is used in snippet
function validateform() {
const name = document.getElementById("email").value;
const password = document.getElementById("pass").value;
if (name.trim() === null || name.trim() === "") {
alert("Name can't be blank");
}
if (password.trim().length < 6) {
alert("Password must be at least 6 characters long.");
}
return;
}
<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">
<title>Document</title>
</head>
<body>
<form name="login" onsubmit="return validateform()" method="post" action="/login_process">
<label for="email">BCBS outlook email</label>
<br>
<input type="email" name="email" id="email" text="BCBS outlook email">
<br>
<label for="pass">Password</label>
<br>
<input type="password" name="pass" id="pass">
<br>
<input type="submit" value="submit">
</form>
</body>
</html>
You need to access the input elements using getElementById(), then make sure you trim your strings to get rid of any spaces:
function validateform() {
var name = document.getElementById("email").value;
var password = document.getElementById("pass").value;
if (name.trim() == null || name.trim() == "") {
alert("Name can't be blank");
return false;
} else if (password.trim().length < 6) {
alert("Password must be at least 6 characters long.");
return false;
}
}
<form name="login" onsubmit="return validateform()" method="post" action="/login_process">
<label for="email">BCBS outlook email</label>
<br>
<input type="email" name="email" id="email" text="BCBS outlook email">
<br>
<label for="pass">Password</label>
<br>
<input type="password" name="pass" id="pass">
<br>
<input type="submit" value="submit">
</form>
<!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">
<title>Document</title>
</head>
<body>
<form name="login" onsubmit="return validateform()" method="post" action="/login_process">
<label for="email">BCBS outlook email</label>
<br>
<input type="email" name="email" id="email" text="BCBS outlook email">
<br>
<label for="pass">Password</label>
<br>
<input type="password" name="pass" id="pass">
<br>
<input type="submit" value="submit">
</form>
</body>
<p id="errorTxt"></p>
<script>
function validateform(){
var name = document.getElementById("email").value;
var password = document.getElementById("pass").value;
if (isNaN(name) || name < 1 || (isNaN(name) || password < 6) ) {
document.getElementById("errorTxt").innerHTML = text;
return false;
}
}
</script>
</body>
</html>
Few mistakes in your code.
The way password is accssed in dom is incorrect.
Since you have used input type email. Broweser will by default check for empty value and valid email.
Here is a working code. as per above modifications.
<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">
<title>Document</title>
<script type="text/javascript">
function validateform() {
var name = document.login.email.value;
var password = document.login.pass.value;
if (name == null || name == "") {
alert("Name can't be blank");
return false;
} else if (password.length < 6) {
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
</head>
<body>
<form name="login" onsubmit="return validateform()" method="post" action="/login_process">
<label for="email">BCBS outlook email</label>
<br>
<input type="email" name="email" id="email" text="BCBS outlook email">
<br>
<label for="pass">Password</label>
<br>
<input type="password" name="pass" id="pass">
<br>
<input type="submit" value="submit">
</form>
</body>
Related
I am getting an error when trying to check if an input field is empty or not. I tried the function with First Name input Field but not working.
I am trying to check if the First Name input field is empty the input border should turn red if not the border should stay the same.
HERE IS MY CODE
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Exercise 2</title>
<script type="text/javascript">
function validateField(fieldID){
check = document.getElementById("fieldID");
if(check.value.length == 0){
check.style.borderColor ="red";
}
}
</script>
</head>
<body>
<h1>Flight Reservation</h1>
<form method="POST" action="">
<label for="userFirstName">First Name:</label><br>
<input type="text" name="userName" id="userFirstName" onblur="validateField(userFirstName);">
<br>
<label for="userLastName">Last Name:</label><br>
<input type="text" name="userLast"id="userLastName">
<br>
<label>class:</label>
<label for="businessRadio">Business</label>
<input type="radio" name="ticketType" id="businessRadio">
<label for="economyRadio">Economy</label>
<input type="radio" name="ticketType" id="economyRadio">
<br>
<label for="wheelchair">Wheelchair</label>
<input type="checkbox" name="wheelchair" id="wheelchair">
<br>
<label for="passengers">Passengers:</label>
<input type="number" name="passengers" id="Passengers">
<br>
<input type="submit" name="Send" >
<input type="reset" name="Cancel">
</form>
</body>
</html>
You are passing fieldId and then trying to access with "" which actually converts the fieldId to a string. I have fixed the issue, please check the code below.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Exercise 2</title>
<script type="text/javascript">
function validateField(fieldID){
check = document.getElementById(fieldID);
if(check.value.length == 0){
check.style.borderColor ="red";
}
}
</script>
</head>
<body>
<h1>Flight Reservation</h1>
<form method="POST" action="">
<label for="userFirstName">First Name:</label><br>
<input type="text" name="userName" id="userFirstName" onblur="validateField('userFirstName');">
<br>
<label for="userLastName">Last Name:</label><br>
<input type="text" name="userLast"id="userLastName">
<br>
<label>class:</label>
<label for="businessRadio">Business</label>
<input type="radio" name="ticketType" id="businessRadio">
<label for="economyRadio">Economy</label>
<input type="radio" name="ticketType" id="economyRadio">
<br>
<label for="wheelchair">Wheelchair</label>
<input type="checkbox" name="wheelchair" id="wheelchair">
<br>
<label for="passengers">Passengers:</label>
<input type="number" name="passengers" id="Passengers">
<br>
<input type="submit" name="Send" >
<input type="reset" name="Cancel">
</form>
</body>
</html>
The error occurs when you are trying to get check.value.length when check === null. So this sentences it's returning null value:
check = document.getElementById("fieldID");
Try to change that line to:
check = document.getElementById(fieldID);
Because you are writting a literal string, not using the variable.
There are two problems with the above code:
1: change below line of code
check = document.getElementById("fieldID");
to
check = document.getElementById(fieldID);
2: use string literals to pass id of the field to funtion called onblur
onblur="validateField(userFirstName);"
replace above line with
onblur="validateField('userFirstName');"
I am making a page that validates user inputs. The username should be in an email format and the password should be 7 or more characters. I think I have the code down, but am struggling to connect the javascript so that it works properly and validates the user inputs.
Here is the code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="assignment.css" />
</head>
<body>
<form>
<h1>Sign in</h1>
<label for="username"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="username" required>
<br><br>
<label for="password"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" required>
<br><br>
<button type="submit" class="signinbtn">Sign In</button>
</form>
function validateForm() {
let regexEmail = / ^ \ w +([\.-] ? \ w +) * # \ w +([\.-] ? \ w +) *(\.\ w { 2, 3 }) + $ /;
let username = document.forms["myForm"]["username"].value;
let password = document.forms["myForm"]["password"].value;
if (
password.length >= 7 || username.match(regexEmail)
) {
alert("Welcome");
return true;
}
else {
alert("error, username must be in email format & password must be 7 or more characters");
return false;
}
</body>
</html>
you are missing a bunch of script tags and the JS needs to be refactored with some minor changes.
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="assignment.css" />
</head>
<body>
<form>
<h1>Sign in</h1>
<label for="username"><b>Username</b></label>
<input
type="text"
placeholder="Enter Username"
name="username"
id="username"
required
/>
<br /><br />
<label for="password"><b>Password</b></label>
<input
type="password"
placeholder="Enter Password"
name="password"
id="password"
required
/>
<br /><br />
<button type="submit" id="btn" class="signinbtn">Sign In</button>
</form>
<script type="text/javascript">
let regexEmail =
/ ^ \ w +([\.-] ? \ w +) * # \ w +([\.-] ? \ w +) *(\.\ w { 2, 3 }) + $ /;
let username = document.getElementById("username").value;
let password = document.getElementById("password").value;
document.getElementById("btn").addEventListener("click", (e) => {
e.preventDefault();
if (password.length >= 7 || username.match(regexEmail)) {
alert("Welcome");
} else {
alert(
"error, username must be in email format & password must be 7 or more characters"
);
}
});
</script>
</body>
</html>
There's a couple of issues I can see here, first of all your JavaScript isn't within <script></script> tags.
Second, the validateForm function you have written isn't attached to your form HTML. Take a look here to see how you can run a function when your form is submitted:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event
Edit: Here's the list of issues:
Your form doesn't have an id attribute but you refer to myForm in your function
Your JavaScript needs to be wrapped in <script> tags
Your regex has spaces in which will prevent it from matching
You're missing a closing curly bracket at the end of your function
You're not attaching the function to your form so it won't be called when it is submitted (as per the link I posted).
Here's the fixed code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="assignment.css" />
</head>
<body>
<form id="myForm">
<h1>Sign in</h1>
<label for="username"><b>Username</b></label>
<input
type="text"
placeholder="Enter Username"
name="username"
required
/>
<br /><br />
<label for="password"><b>Password</b></label>
<input
type="password"
placeholder="Enter Password"
name="password"
required
/>
<br /><br />
<button type="submit" class="signinbtn">Sign In</button>
</form>
<script>
function validateForm() {
let regexEmail = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
let username = document.forms["myForm"]["username"].value;
let password = document.forms["myForm"]["password"].value;
if (password.length >= 7 || username.match(regexEmail)) {
alert("Welcome");
return true;
} else {
alert(
"error, username must be in email format & password must be 7 or more characters"
);
return false;
}
}
const formEle = document.getElementById("myForm");
formEle.addEventListener("submit", validateForm);
</script>
</body>
</html>
Re:your comment - you have a function and you have an HTML form. In the original code, where is your function called? What triggers the validation on the form fields to be run? In the code I've provided I've attached your function to the submit event of the form so when the form is submitted, your function is called. There's other ways this could be handled - adding a click handler on the button, adding a change handler to the form fields, etc. etc.
I am trying to create a simple form using Javascript, but I am facing an issue while trying to display somethings on the console. The issue here is that whenever I click on the submit button, Nothing is displayed on the console despite giving the command e.preventdefault(). At present I want the text Hello to be displayed on console when it satisfies the condition, but even though the condition is satisfied, nothing is displayed.
Herewith attaching the Javascript and HTML code for the same
const passlength = 10;
const firstname = document.getElementById("firstname");
const lastname = document.getElementById("lastname");
const emailid = document.getElementById("emailid");
const password = document.getElementById("pass");
const confirmpassword = document.getElementById("passconfirm");
const phonenumber = document.getElementById("phno");
const form = document.querySelector(".mainform");
function testfunc() {
console.log(type(emailid));
}
function checkpass(pass) {
if (pass>=passlength) {
console.log("Hello");
}
else{
console.log("Out");
}
}
form.addEventListener('submit',function(e){
e.preventDefault();
checkpass(password);
})
<!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">
<title>Register with us</title>
</head>
<body>
<div class="mainform">
<form>
<label for="firstname">First name:</label>
<input type="text" id="firstname" name="firstname"><br>
<label for="lastname">Last name:</label>
<input type="text" id="lastname" name="lastname"><br>
<label for="emailid">Email ID:</label>
<input type="email" id="emailid" name="emailid"><br>
<label for="pass">Enter password:</label>
<input type="password" id="pass" name="pass"> <br>
<label for="passconfirm">Confirm password:</label>
<input type="password" id="passconfirm" name="passconfirm"> <br>
<label for="phno">Phone number:</label>
<input type="number" id="phno" name="phno">
<br> <br>
<input type="submit" value="Submit" id="submit">
</form>
</div>
</body>
</html>
The problem is in your If statement. You are comparing a number with an HTML element. You still need these two.
.value returns the value of the html element
https://www.w3schools.com/jsref/prop_text_value.asp
.length returns the length of a string
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/String/length
This is how you compare two numbers, as you intended.
So your new IF condition must be:
(pass.value.length>=passlength)
I've been trying to make a simple login system (local) and I'm a bit confused.. How can I take the input the user wrote into the text field print it in console and store it in a variable?
My HTML code:
<!DOCTYPE html>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="username.js"></script>
<script src="password.js"></script>
</head>
<body>
<title>Login #1</title>
<h2>Simple login system</h2>
<form name="">
<label for="text1">Username:</label>
<input type="text" name="text1">
<label for="text2">Password:</label>
<input type="text" name="text2">
<button onclick="password(), username()">login</button>
</form>
</body>
</html>
For my JS I wanted to have the ''password() and username()'' functions checking both seperatly in seperate files.
JS Password file:
const Psword = 'Password9' //just an example
function password() {
console.log(Psword)
// if (user input from password field) = Psword
// alert('Login sucessfull redirecting!)
// else{
// alert('Username or password are incorrect')
// }
}
JS Username file:
var Username = 'Subject09'
function username() {
console.log(Username)
// if (user input from username field) = Username
// alert('Login sucessfull redirecting!)
// else{
// alert('Username or password are incorrect')
// }
}
EDIT: Added my JS code.
(Note: I've split my code into 2 diffrent JS files because I just want it to be simple in the outcome.)
We can do a form submit using onsubmit event.
UPDATE: I am showing you the form submit approach.
const form = document.querySelector("form");
form.addEventListener("submit",(e)=>{
e.preventDefault();
if(form["text1"].value && form["text2"].value){
console.log("Submitted the form");
form.reset();
}else{
console.log("Provide required values");
}
})
<!DOCTYPE html>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="username.js"></script>
<script src="password.js"></script>
</head>
<body>
<title>Login #1</title>
<h2>Simple login system</h2>
<form>
<div>
<label>Username:</label>
<input type="text" name="text1" >
</div>
<div>
<label>Password:</label>
<input type="text" name="text2">
<div>
<button type="submit">login</button>
</form>
</body>
</html>
Set ids to you input and your button. You can prevent submitting by adding type="button" to your button.
Simply set an onclick event on your button, and get your inputs values.
<body>
<title>Login #1</title>
<h2>Simple login system</h2>
<form>
<label for="text1">Username:</label>
<input type="text" name="text1" id="username">
<label for="text2">Password:</label>
<input type="text" name="text2" id="password">
<button type="button" id="submitBtn">login</button>
</form>
window.onload = function() {
document.getElementById('submitBtn').addEventListener('click', onSubmit);
}
function onSubmit() {
console.log(document.getElementById('username').value);
console.log(document.getElementById('password').value);
// Do what you want with data
// You can submit with .submit()
document.forms['form'].submit();
}
I am trying to perform a simple task. I want to validate a form or show a message stating 'Please complete the form!' What am I overlooking because all works except the message? How can I achieve this or am I simply just missing something? I have tried placing the script at the top and bottom, but I want on the bottom because I want the page to load faster and not pause for the JS.
<!Doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Index</title>
<!--[if it IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![end if]-->
<link rel="stylesheet" href="styles.css">
</head>
<body>
<form action="login.php" method="post" id="loginForm">
<fieldset>
<legend>Login</legend>
<div><label for="email">Email Address</label>
<input type="email" name="email" id="email" required></div>
<div><label for="password">Password</label>
<input type="password" name="password" id="password" required></div>
<div><label for="submit"></label><input type="submit" value="Login →" id="submit"></div>
</fieldset>
</form>
<script src="login.js"></script>
</body>
</html>
JS
function validateForm() {
'use strict';
var email = document.getElementById('email');
var password = document.getElementById('password');
if ( (email.value.length > 0) && (password.value.length > 0) ) {
return true;
} else {
alert('Please complete the form!');
return false;
}
}
function init() {
'use strict';
if (document && document.getElementById) {
var loginForm = document.getElementById('loginForm');
loginForm.onsubmit = validateForm;
}
}
window.onload = init;
If you want to use your own validation instead of the browser's built-in checking for required fields, remove the required attributes from your <input> tags.
DEMO