Why doesn't my form show a validation error? - javascript

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

Related

Unable to validate form using js

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>

Validating User Inputs Using Javascript

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.

Bootstrap 5 validating on submit but not showing invalid field hints

I boiled down an example of a Laravel app that uses Bootstrap 5.0 and Javascript. The validation works at the Javascript level but incorrectly filled in or empty fields are never highlighted by Bootstrap for entry on failure. Your specific route for stackexchange.blade.php must be coded Route::any('Route','stackexchange')'. My question is why this is happening? Can you suggest a fix.
//pagescript2.js
function sendJSON(ip_address)
{
let o = {
ip:ip_address
}
alert(JSON.stringify(o));
//call Zapier webhook with Fetch API.
return true;
}
function VForm(ip_address)
{
//Check forms validity, call redirecting method.
if ($('form')[0].checkValidity()) {
sendJSON(ip_address);
//This redirects as expected
window.location.href="https://www.yahoo.com";
}
return false;
}
<!-- stackexchange.blade.php-->
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous">
</head>
<body>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script type="text/javascript" src="{{asset('js/landingpages/pagescript2.js')}}"></script>
<form method = "POST" onsubmit="return VForm('<?php echo $_SERVER['REMOTE_ADDR'];?>');" class="needs-validation" novalidate>
#csrf
<div>
<label for="fname">First Name</label>
<input id= "fname" class="form-control" name="fname" type = "text" required />
<label for="email">Email Address</label>
<input id = "email" class="form-control" name="email" type="email" required/>
</div>
<button value="Submit" type="submit">Send Up!!</button>
</form>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-U1DAWAznBHeqEIlVSCgzq+c9gqGAJn5c/t99JyeKa9xxaYpSvHU5awsuZVVFIhvj" crossorigin="anonymous"></script>
</body>
</html>
you just need to delete this code novalidate, so that the validation works well
//pagescript2.js
function sendJSON(ip_address)
{
let o = {
ip:ip_address
}
alert(JSON.stringify(o));
//call Zapier webhook with Fetch API.
return true;
}
function VForm(ip_address)
{
//Check forms validity, call redirecting method.
if ($('form')[0].checkValidity()) {
sendJSON(ip_address);
//This redirects as expected
window.location.href="https://www.yahoo.com";
}
return false;
}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous">
</head>
<body>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script type="text/javascript" src="{{asset('js/landingpages/pagescript2.js')}}"></script>
<form method = "POST" onsubmit="return VForm('<?php echo $_SERVER['REMOTE_ADDR'];?>');" class="needs-validation">
<div>
<label for="fname">First Name</label>
<input id= "fname" class="form-control" name="fname" type = "text" required />
<label for="email">Email Address</label>
<input id = "email" class="form-control" name="email" type="email" required/>
</div>
<button value="Submit" type="submit">Send Up!!</button>
</form>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-U1DAWAznBHeqEIlVSCgzq+c9gqGAJn5c/t99JyeKa9xxaYpSvHU5awsuZVVFIhvj" crossorigin="anonymous"></script>
</body>
</html>

My HTML form validator in Javascript doesn't seem to be working

I've written a validator for my HTML although I'm not sure where I'm going wrong.
What I'm trying to do below is determine if there is any text in the "First Name" box altogether. There is underlying css to the code but I believe my issue is surrounding my onsubmit and validate function as nothing in the javascript seems to be running once I click the submit button.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>NewPatientForm</title>
<link rel="stylesheet" type="text/css" href="NewPatient.css">
<script>
function validate() {
var invalid = false;
if(!document.Firstname.value.length) {
invalid = true;
}
if(invalid) {
document.getElementById("form-error").style.display = "inline-block";
return false; //to make the text appear
}
return true;
}
</script>
</head>
<body>
<form id="NewPatientForm" method="post" action="#" onsubmit="return validate();">
<div class="form-element">
<p id="form-error">All fields are required</p>
</div>
<div>
<label for="Firstname">First Name
<input type="text" name="Firstname" placeholder="First Name" id="Firstname">
</label>
</div>
<div>
<input type="submit" name="submit-button" value="Submit">
</div>
</form>
</body>
</html>
Looks like the culprit was your attempt to access Firstname on the document object.
I replaced it with the more standard document.getElementById() method and its working.
Some reading on this: Do DOM tree elements with ids become global variables?
function validate() {
var invalid = false;
if(!document.getElementById('Firstname').value.length) {
invalid = true;
}
if(invalid) {
document.getElementById("form-error").style.display = "inline-block";
return false;
}
return true;
}
#form-error {
display: none;
}
<form id="NewPatientForm" method="post" action="#" onsubmit="return validate()">
<div class="form-element">
<p id="form-error">All fields are required</p>
</div>
<div>
<label for="Firstname">First Name
<input type="text" name="Firstname" placeholder="First Name" id="Firstname">
</label>
</div>
<div>
<input type="submit" name="submit-button" value="Submit">
</div>
</form>
There are a couple of typos, and I'll suggest something else as well. First, a fix or three in the code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>NewPatientForm</title>
<script>
function validate() {
const invalid = document.getElementById("Firstname").value.length == 0;
if(invalid) {
document.getElementById("form-error").style.display = "inline-block";
return false; //to make the text appear
}
return true;
}
</script>
</head>
<body>
<form id="NewPatientForm" method="post" action="#" onsubmit="return validate();">
<div class="form-element">
<p id="form-error">All fields are required</p>
</div>
<div>
<label for="Firstname">First Name
<input type="text" name="Firstname" placeholder="First Name" id="Firstname">
</label>
</div>
<div>
<input type="submit" name="submit-button" value="Submit">
</div>
</form>
</body>
</html>
My suggestion is that you also look into built-in HTML form validation attributes. I'm thinking you're reinventing the wheel for things like requiring a non-empty Firstname. Why not this instead of JavaScript?
<input type="text" name="Firstname" id="Firstname" placeholder="First Name" required />
And many others, like minlength="", min="", step="", etc.
Plus there's still a JavaScript hook into the validation system with .checkValidity() so you can let the built-in validation do the heavy lifting, and then throw in more of your own custom aspects too.

More Simple Password System Stuff

Sorry guys, first time playing around with this. Here's the HTML:
<!DOCTYPE html>
<html>
<head>
<title>SuM BUTtonsS DOe</title>
<link rel="stylesheet" href="buttons.css"/>
</head>
<body>
<p>Please enter the password</p>
<form id="enter" onSubmit="javascript:passCheck()">
<input id="password" type="password" placeholder="Password">
</form>
<p id="incorrect"><em>INCORRECT PASSWORD</em></p>
<script type="text/javascript">
function passCheck() {
var input = document.getElementById('password').value;
if (input == 'herro') {
window.alert("IT WORKS!!");
}
else {
var incorrect = document.getElementById('incorrect');
incorrect.style.display = "block";
}
}
</script>
</body>
</html>
When I enter the wrong password, INCORRECT PASSWORD comes up, but only for a fraction of a second. Then it's gone again. No idea why.
UPDATE:
<!DOCTYPE html>
<html>
<head>
<title>SuM BUTtonsS DOe</title>
<link rel="stylesheet" href="buttons.css"/>
</head>
<body>
<p>Please enter the password</p>
<form id="enter" onSubmit="javascript:passCheck()">
<input id="password" type="password" placeholder="Password">
</form>
<p id="incorrect"><em>INCORRECT PASSWORD</em></p>
<script type="text/javascript">
function passCheck() {
var input = document.getElementById('password').value;
if (input == 'herro') {
window.alert("IT WORKS!!");
}
else {
var incorrect = document.getElementById('incorrect');
incorrect.style.display = "block";
return false;
}
}
</script>
</body>
</html>
On submit, the form will trigger the default action, which in this case is to submit the contents to the same page (for lack of an action property).
So what you're seeing is the JavaScript runs and changes the style to show the error message, then the page reloads.
To ensure the page doesn't reload put return false at the end of passCheck. Better would be to use addEventListener and event.preventDefault(), but that's a little bit more involved.
<p>Please enter the password</p>
<form id="enter" onSubmit="passCheck(); return false;">
<input id="password" type="password" placeholder="Password">
<input type="submit" value="Submit"/>
</form>
<p id="incorrect" style="display: none"><em>INCORRECT PASSWORD</em></p>
<script type="text/javascript">
function passCheck() {
var input = document.getElementById('password').value;
if (input == 'herro') {
window.alert("IT WORKS!!");
}
else {
var incorrect = document.getElementById('incorrect');
incorrect.style.display = "block";
}
}
</script>

Categories