Basic Form Validation with the DOM - javascript

JS newbie here. I have been trying to learn basic front end on my own and tried to create this form validation but my error messages are not working properly. If a field is empty I want each field to return their own error message but somethings are overwriting others.
Attaching the codes and the screenshot.
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Form Validator</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<form id="all-form" action="">
<h3>Register with us</h3>
<div class="form-control">
<label for="Username">Username</label>
<input id="user" type="username" placeholder="Enter Username" />
<small>error message</small>
</div>
<div class="form-control">
<label for="email">Email</label>
<input id="mail" type="email" placeholder="Enter Email" />
<small>error message</small>
</div>
<div class="form-control">
<label for="password">Password</label>
<input id="pass" type="password" placeholder="Enter Password" />
<small>error message</small>
</div>
<div class="form-control">
<label for="password">Confirm Password</label>
<input id="pass-again" type="password" placeholder="Enter Password Again" />
<small>error message</small>
</div>
<button type="submit" class="submit-btn">Submit</button>
</div>
</form>
<script src="app.js"></script>
</body>
</html>
:root{
--success-color:#2ecc71;
--error-color:#e74c3c;
}
*{
margin:0px;
padding: 0px;
box-sizing: border-box;
font-family: Arial, Helvetica, sans-serif;
}
.container{
position: relative;
top:10em;
margin: auto;
background-color: #fff;
width: 400px;
border-radius: 5px;
box-shadow:0 2px 10px rgba(0,0,0, 0.3);
}
form{
padding:20px 20px;
}
h3 {
text-align: center;
}
label, input{
display: block;
margin:5px;
width: 90%;
}
label{
padding-top: 15px;
padding-right: 15px;
text-align: left;
margin-bottom: 5px;
}
input{
padding:3px;
border-radius: 5%;
font-size: 14px;
}
.submit-btn{
display: block;
padding:10px;
background-color: royalblue;
color: white;
cursor: pointer;
border-radius: 4px;
font-size: 16px;
margin-top:20px;
width: 100%;
}
input:focus{
outline:0;
border-color: #777;
}
.form-control.success input{
border-color: var(--success-color);
}
.form-control.error input{
border-color: var(--error-color);
}
.form-control small{
color:var(--error-color);
position: relative;
bottom:1px;
left:7px;
visibility: hidden;
}
.form-control.error small{
visibility: visible;
}
// Selectors
const username = document.querySelector("#user");
const mail = document.querySelector("#mail");
const pass = document.querySelector("#pass");
const passAgain= document.querySelector("#pass-again");
const sbtBtn = document.querySelector(".submit-btn");
const form = document.querySelector("#all-form");
// Event Listeners
function showError(input,message){
const formControl = input.parentElement;
formControl.className = "form-control error";
const small = document.querySelector("small");
small.innerText = message;
}
function showSuccess(input){
const formControl = input.parentElement;
formControl.className = "form-control success";
}
form.addEventListener("submit",checkAll);
function checkAll(e){
e.preventDefault();
if(username.value === ""){
showError(username, "Username is required");
} else {
showSuccess(username);
}
if(mail.value === ""){
showError(mail, "E-mail is required");
} else {
showSuccess(mail);
}
if(pass.value === ""){
showError(pass, "Password is required");
} else {
showSuccess(pass);
}
if(passAgain.value === ""){
showError(passAgain, "Enter password again please");
} else {
showSuccess(passAgain);
}
}

Related

Can anyone help me find out what's wrong with my form validation code?

<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="./css/createanaccount.css">
<script src="https://kit.fontawesome.com/c90e5c3147.js" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<div class="header">
<h2>Create An Account</h2>
</div>
<form class="form" id="form">
<div class="form-control">
<label>Full Name</label>
<input type="text" placeholder="John Doe" id="fullname">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<span>Error Message</span>
</div>
<div class="form-control">
<label>Email</label>
<input type="email" placeholder="johndoe#gmail.com" id="email">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<span>Error Message</span>
</div>
<div class="form-control">
<label>Phone Number</label>
<input type="tel" placeholder="" id="phonenumber">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<span>Error Message</span>
</div>
<div class="form-control">
<label>Password</label>
<input type="password" placeholder="" id="password">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<span>Error Message</span>
</div>
<div class="form-control">
<label>Confirm Password</label>
<input type="password" placeholder="Confirm your password" id="confirmpassword">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<span>Error Message</span>
</div>
<button>Create Account</button>
</form>
</div>
<script src="js/createanaccount.js"></script>
</body>
</html>
#import url('https://fonts.googleapis.com/css2?family=Poppins&display=swap');
*{
box-sizing: border-box;
}
body{
background-color: #9b59b6;
font-family: "Poppins", sans-serif;
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
margin: 0;
}
span{
font-size: 0.8rem;
}
.container{
background-color: #fff;
border-radius: 5px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
overflow: hidden;
width: 400px;
max-width: 100%;
}
.header{
background-color: #f7f7f7;
border-bottom: 1px solid #f0f0f0;
padding: 20px 40px;
}
.header h2{
margin: 0;
}
.form{
padding: 30px 40px;
}
.form-control{
margin-bottom: 10px;
padding-bottom: 20px;
position: relative;
}
.form-control label{
display: inline-block;
margin-bottom: 5px;
}
.form-control input{
border: 2px solid #f0f0f0;
border-radius: 4px;
display: block;
font-family: inherit;
font-size: 14px;
padding: 10px;
width: 100%;
}
.form-control.success input{
border-color: #2ecc71;
}
.form-control.error input{
border-color: #e74c3c;
}
.form-control i{
position: absolute;
top: 40px;
right: 10px;
visibility: hidden;
}
.form-control.success i.fa-check-circle{
color: #2ecc71;
visibility: visible;
}
.form-control.error i.fa-exclamation-circle{
color: #e74c3c;
visibility: visible;
}
.form-control span{
visibility: hidden;
position: absolute;
bottom: 0;
left: 0;
}
.form-control.error span{
color: #e74c3c;
visibility: visible;
}
.form button{
background-color: #8e44ad;
border: 2px solid #8e44ad;
border-radius: 4px;
color: #fff;
display: block;
font-family: inherit;
font-size: 16px;
padding: 10px;
width: 100%;
}
.form button:hover{
cursor: pointer;
box-shadow: 0 .5rem 1.5rem rgba(0, 0, 0, 0.8);
}
const form = document.getElementById("form");
const fullname = document.getElementById("fullname");
const email = document.getElementById("email");
const phonenumber = document.getElementById("phonenumber");
const password = document.getElementById("password");
const confirmpassword = document.getElementById("confirmpassword");
form.addEventListener("submit", e => {
e.preventDefault();
checkInputs();
});
function checkInputs(){
//Get the values from the inputs
const fullnameValue = fullname.value.trim();
const emailValue = email.value.trim();
const phonenumberValue = phonenumber.value.trim();
const passwordValue = password.value.trim();
const confirmpasswordValue = confirmpassword.value.trim();
if(fullnameValue === ""){
//Show error
//Add error class
setErrorFor(fullname, 'Name cannot be blank');
}else{
//Add success class
setSuccessFor(fullname);
}
if(emailValue === ""){
setErrorFor(email, 'Email cannot be blank');
}else if(!isEmail(emailValue)){
setErrorFor(email, "Email is not valid");
}else{
setSuccessFor(email);
}
if(phonenumberValue === ""){
setErrorFor(phonenumber, 'Phone number cannot be blank');
}else if(!isPhoneNumber(phonenumberValue)){
setErrorFor(phonenumber, "Phone number is not valid");
}else{
setSuccessFor(fullname);
}
if(passwordValue === ""){
setErrorFor(password, 'Password cannot be blank');
}else if(passwordValue < 8){
setErrorFor(password, "Minimum password length is 8 characters");
}else{
setSuccessFor(password);
}
if(confirmpasswordValue === ""){
setErrorFor(confirmpassword, 'Confirm password cannot be blank');
}else if(passwordValue !== confirmpasswordValue){
setErrorFor(confirmpassword, 'Passwords do not match');
}else{
setSuccessFor(confirmpassword);
}
}
function setErrorFor(input, message){
const formControl = input.parentElement; // .form-control
const span = document.querySelector("span");
//Add error message inside span
span.innerText = message;
//Add error class
formControl.className = 'form-control error';
}
function setSuccessFor(input){
const formControl = input.parentElement;
formControl.classname = 'form-control success';
}
function isEmail(email){
return /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email);
}
function isPhoneNumber(phonenumber){
return /^\d{10}$/.test(phonenumber);
}
I am writing this code for a form validation for a project I am doing but it isn't responding as needed too. The error messages given aren't the ones I specified and/ or only appear on the first textbox and it doesn't put out the setSuccessFor function. Any help help would be appreciated
Image of incorrect error messages for reference
The issue is you're targeting the span with document.querySelector('span') which picks up the first span in the entire document. You want to call that from the reference point of the container div. Also, rather than parentElement (which is fine), I prefer closest() since it will be flexible if your html structure changes. Finally, you can add and remove classes via classList, which free's up the need for you to overwrite the entire set of class names for any given element
function setErrorFor(input, message){
const formControl = input.closest('.form-control');
const span = formControl.querySelector("span");
span.innerText = message;
formControl.classList.remove('success');
formControl.classList.add('error');
}
function setSuccessFor(input){
const formControl = input.closest('.form-control');
formControl.classList.add('success');
formControl.classList.remove('error');
}

my javascript event listener doesn't work and it still submits page - cannot read property 'addEventListener' of null [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Uncaught TypeError: Cannot read property 'value' of null [duplicate]
(10 answers)
Closed last month.
I am trying to validate a contact form but none of my JavaScript is working but I guess my event listener is the problem because my page still refreshes on click of the button. It returned an error in the console
Uncaught TypeError: Cannot read property 'addEventListener' of null
const form = document.getElementById('form');
const client = document.getElementById('name');
const email = document.getElementById('email');
const message = document.getElementById('text-message');
// Show input error message
function showError(input, message) {
const formControl = input.parentElement;
formControl.className = 'form-control error';
const small = formControl.querySelector('small');
small.innerText = message;
}
// Show success outline
function showSuccess(input) {
const formControl = input.parentElement;
formControl.className = 'form-control success';
}
// Check email is valid
function checkEmail(input) {
const re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (re.test(input.value.trim())) {
showSuccess(input);
} else {
showError(input, 'Email is not valid');
}
}
// Check required fields
function checkRequired(inputArr) {
inputArr.forEach(function(input) {
if (input.value.trim() === '') {
showError(input, `${getFieldName(input)} is required`);
} else {
showSuccess(input);
}
});
}
// Get fieldname
function getFieldName(input) {
return input.id.charAt(0).toUpperCase() + input.id.slice(1);
}
// Event listeners
form.addEventListener('submit', function(e) {
e.preventDefault();
checkRequired([client, email, message]);
checkEmail(email);
});
.container {
display: flex;
justify-content: flex-start;
flex-direction: column;
width: 30rem;
padding: 0rem 10rem; }
.container .submit-btn {
margin-top: 4rem; }
.container input {
width: 20rem;
height: 2rem;
background-color: var(--color-blue);
border: 1px solid #0652b9;
border-color: #0652b9;
border-radius: 2.5rem;
display: block;
color: #161616;
text-indent: 15px; }
.container input:focus {
outline: 0;
border-color: #ff8b2c; }
.container textarea {
width: 20rem;
height: 10rem;
background-color: var(--color-blue);
border: 1px solid #0652b9;
border-color: #0652b9;
border-radius: 1.5rem;
color: #161616;
text-indent: 15px; }
.container textarea:focus {
outline: 0;
border-color: #ff8b2c; }
.container ::placeholder {
color: #161616;
opacity: 0.5; }
.container .form-control {
position: relative; }
.container .form-control.success input {
border-color: green; }
.container .form-control.error input {
border-color: red; }
.container .form-control small {
color: red;
bottom: 0;
left: 0;
visibility: hidden; }
.container .form-control.error small {
visibility: visible; }
button {
width: 7rem;
height: 3rem;
background: #0652b9;
border-style: none;
border-radius: 2.5rem;
color: #ffffff; }
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="../css/main.css" />
</head>
<body>
<section class="container">
<form action="/" method="GET" id="form" class="form">
<div class="form-control">
<!-- <label for="name">Name</label> -->
<input type="text" id="client" placeholder="Your name">
<small>Error message</small>
</div>
<div class="form-control">
<!-- <label for="email">Email</label> -->
<input type="text" id="email" placeholder="Your email">
<small>Error message</small>
</div>
<div class="form-control">
<!-- <label for="message">Message</label> -->
<textarea name="message" id="text-message" rows="7" placeholder="Say something about your project"></textarea>
<small>Error message</small>
</div>
<button class="submit-btn" type="submit">Send message</button>
</form>
</section>
<script src="validation.js"></script>
</body>
</html>
Your selector for the variable client should be client instead of name
const form = document.getElementById('form');
const client = document.getElementById('client');
const email = document.getElementById('email');
const message = document.getElementById('text-message');
// Show input error message
function showError(input, message) {
const formControl = input.parentElement;
formControl.className = 'form-control error';
const small = formControl.querySelector('small');
small.innerText = message;
}
// Show success outline
function showSuccess(input) {
const formControl = input.parentElement;
formControl.className = 'form-control success';
}
// Check email is valid
function checkEmail(input) {
const re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (re.test(input.value.trim())) {
showSuccess(input);
} else {
showError(input, 'Email is not valid');
}
}
// Check required fields
function checkRequired(inputArr) {
inputArr.forEach(function(input) {
if (input.value.trim() === '') {
showError(input, `${getFieldName(input)} is required`);
} else {
showSuccess(input);
}
});
}
// Get fieldname
function getFieldName(input) {
return input.id.charAt(0).toUpperCase() + input.id.slice(1);
}
// Event listeners
form.addEventListener('submit', function(e) {
e.preventDefault();
checkRequired([client, email, message]);
checkEmail(email);
});
.container {
display: flex;
justify-content: flex-start;
flex-direction: column;
width: 30rem;
padding: 0rem 10rem; }
.container .submit-btn {
margin-top: 4rem; }
.container input {
width: 20rem;
height: 2rem;
background-color: var(--color-blue);
border: 1px solid #0652b9;
border-color: #0652b9;
border-radius: 2.5rem;
display: block;
color: #161616;
text-indent: 15px; }
.container input:focus {
outline: 0;
border-color: #ff8b2c; }
.container textarea {
width: 20rem;
height: 10rem;
background-color: var(--color-blue);
border: 1px solid #0652b9;
border-color: #0652b9;
border-radius: 1.5rem;
color: #161616;
text-indent: 15px; }
.container textarea:focus {
outline: 0;
border-color: #ff8b2c; }
.container ::placeholder {
color: #161616;
opacity: 0.5; }
.container .form-control {
position: relative; }
.container .form-control.success input {
border-color: green; }
.container .form-control.error input {
border-color: red; }
.container .form-control small {
color: red;
bottom: 0;
left: 0;
visibility: hidden; }
.container .form-control.error small {
visibility: visible; }
button {
width: 7rem;
height: 3rem;
background: #0652b9;
border-style: none;
border-radius: 2.5rem;
color: #ffffff; }
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="../css/main.css" />
</head>
<body>
<section class="container">
<form action="/" method="GET" id="form" class="form">
<div class="form-control">
<!-- <label for="name">Name</label> -->
<input type="text" id="client" placeholder="Your name">
<small>Error message</small>
</div>
<div class="form-control">
<!-- <label for="email">Email</label> -->
<input type="text" id="email" placeholder="Your email">
<small>Error message</small>
</div>
<div class="form-control">
<!-- <label for="message">Message</label> -->
<textarea name="message" id="text-message" rows="7" placeholder="Say something about your project"></textarea>
<small>Error message</small>
</div>
<button class="submit-btn" type="submit">Send message</button>
</form>
</section>
<script src="validation.js"></script>
</body>
</html>
It gets submitted duo to an error is in there. Just change:
const client = document.getElementById('name');
to
const client = document.getElementById('client');

How to change the color of a specific box when it isn't filled out correctly

I'm trying to create checks to validate the input of a user, such as whether he filled it out and is it the correct input. I want it to highlight the fields that contain an error.
I already asked and I was told to create a class however I don't know how to do that.
There is also
<!DOCTYPE HTML>
<html lang="en">
<head>
<title>Form Validation</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="styles/styles.css">
<link rel="stylesheet" type="text/css" href="styles/forms.css">
<script type="text/javascript">
window.onload=init;
var form;
function init() {
form = document.getElementById('testform');
form.addEventListener("submit", checkSubmit, false);
form.addEventListener("reset", checkReset, false);
form['colour'].addEventListener("change", checkSubmit, false);
form['name'].focus();
}
String.prototype.trim=function() {
return this.replace(/^\s+1\s+$/g, '');
}
function whichButton(name) {
var buttons=document.getElementsByName(name);
for (var i in buttons) {
if(buttons[i].checked) return buttons[i].value
}
return false;
}
function showOtherColour() {
document.getElementById('othercolour').style.visibility=
form['colour'].value=='other' ? 'visible' : 'hidden';
}
function checkSubmit() {
error = new Array();
//Fill the array with the error value
form['name'].value=form['name'].value.trim();
form['email'].value=form['email'].value.trim();
form['town'].value=form['town'].value.trim();
form['state'].value=form['state'].value.trim();
form['postcode'].value=form['postcode'].value.trim();
form['dob'].value=form['dob'].value.trim();
form['height'].value=form['height'].value.trim();
//Check required fields
if(!form['name'].value)
error.push('Missing Name');
if(!form['email'].value)
error.push('Missing Email Address');
if(!form['password'].value)
error.push('Missing Password');
//Check valid email address
var pattern=/^[a-zA-Z0-9._%-]+#[a-zA-Z0-9.-]+(\.[a-zA-Z]{2,4})$/;
if(!form['email'].value.match(pattern))
error.push('Invalid Email Address');
//Check State
//Check Post Code has 4 digits
var pattern=/^\d{4}$/;
if(!form['postcode'].value.match(pattern))
error.push('Invalid Post Code');
//Check password matches confirmation
//var password = ;
/*
if(!form['passwordConfirm'].value.match(password)){
error.push("Passwords don't match");
}*/
console.log(form['confirm'].value);
console.log(form['password'].value);
if(!form['confirm'].value.match(form['password'].value)){
error.push('Passwords do not match');
}
//passwords is too short
if (!form['password'].value.length < 4) {
error.push("Password is too short (Minimum 4 characters)");
}
//height is not a number
if (isNaN(Number(form['height'].value))) {
error.push("Height is not a number");
}
//Check that one Gender item is selected
if(whichButton('gender')===false)
error.push('Please choose a Gender');
//Check that "Other" field is filled
if (!form['colour'].value ||
(form['colour'].value=='other' && !form['othercolour'].value))
error.push('Colour is not selected');
if(error.length) { // if there are errors
alert(error.join("\n"))
return false;
}
else return true;
//return confirm("This will submit the form"); //Temporary placeholder
}
function checkReset() {
return confirm("This will clear the form data");
}
</script>
<style type="text/css">
body,td,th {
font-size: 0.9em;
}
</style>
</head>
<body>
<div id="body">
<h1>Form Validation</h1>
<form action="http://test.miform.net" method="post" id="testform">
<fieldset>
<label>Name<br><input type="text" name="name" class="wide"></label>
<label>Email Address<br><input type="text" name="email" class="wide"></label>
</fieldset>
<fieldset>
<label>Address<br><input type="text" name="street" class="wide"></label>
<label>Town<br><input type="text" name="town" class="narrow"></label>
<label>State<br><input type="text" name="state" class="narrow"></label>
<label>PostCode<br><input type="text" name="postcode" class="narrow"></label>
</fieldset>
<fieldset>
<label>Password<br><input type="password" name="password" class="medium"></label>
<label>Confirm Password<br><input type="password" name="confirm" class="medium"></label>
</fieldset>
<fieldset>
<label>Date of Birth<br><input type="text" name="dob" class="medium"></label>
<label>Height<br><input type="text" name="height" class="medium"></label>
</fieldset>
<fieldset>
<legend>Gender</legend>
<label><input type="radio" name="gender" value="f">Female</label>
<label><input type="radio" name="gender" value="m">Male</label>
</fieldset>
<fieldset>
<label>Colour
<select name="colour">
<option value="">Select...</option>
<option value="black">Black</option>
<option value="white">White</option>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="cyan">Cyan</option>
<option value="magenta">Magenta</option>
<option value="yellow">Yellow</option>
<option value="other">Other</option>
</select>
</label>
<input type="text" id="othercolour">
</fieldset>
<input type="reset" name="reset" value="Clear Form">
<input type="submit" name="send" value="Send Off">
</form>
</div>
</body>
</html>
The CSS (form.css):
body {
font-family: sans-serif;
font-size: .9em;
}
form {
width: 26em;
}
label {
font-weight: bold;
float: left;
}
input.wide {
padding: .125em;
width: 25.125em;
}
input.medium {
padding: .125em;
width: 12em;
}
input.narrow {
padding: .125em;
width: 8em;
}
#othercolour {
visibility: hidden;
}
The style.css
body {
font-family: sans-serif;
font-size: .9em;
background-color: rgb(166, 183, 183);
color: black;
}
div#body {
width: 30em;
margin: auto;
padding: 1em 2em;
background-image: url(background.png);
background-repeat: repeat-x;
background-color: rgb(224, 230, 230);
}
h1,h2 {
color: rgb(47, 79, 79);
}
h2 {
margin: .25em 0em .25em 0em;
}
a {
text-decoration: none;
color: rgb(132, 156, 156);
color: white;
font-weight: bold;
}
a:hover {
color: yellow;
}
td, th {
vertical-align: top;
text-align: left;
}
img {
border: 0px;
}
p, .clear {
qclear: both;
}
#catalog {
float: left;
width: 50%;
}
#content {
float: right;
width: 46%;
}
#cart {
border: 1px solid #cccccc;
padding: 0em .5em;
}
#cart form {
display: inline;
}
#cart input.text {
width: 2em;
text-align: right;
}
#welcome {
}
#navigation {
}
#navigation span {
color: rgb(131, 155, 155);
}
#navigation ul {
list-style: none;
padding: 0;
margin: 0;
}
#navigation li {
float: left;
background-color: pink;
border-bottom: solid 1px;
}
#navigation li a {
display: block;
width: 8em;
text-decoration: none;
font-weight: bold;
text-align: center;
padding: .25em;
background-color: rgb(97, 124, 124);
}
#navigation li a:hover {
background-color: rgb(47, 79, 79);
}
You can set the input's CSS border-color property to highlight the field.
var input = document.querySelector('input'),
form = document.querySelector('form');
form.addEventListener('submit', function(e){
e.preventDefault();
if(!input.value.trim()){//if value of input is empty
input.style.borderColor = "red";
} else {
input.style.borderColor = "green";
}
});
<form>
<input placeholder="Enter something">
<br/>
<button>Validate</button>
</form>
If you use the HTML5 validation attributes, then all you’ll need is to set up a CSS rule using the :invalid pseudo class:
:invalid { . . . }
To add a class, use JavaScript's classList.add() function.
Example
function check() {
var element = document.getElementById("input");
if (element.value != "") {
document.write("Valid!");
} else {
element.classList.add("invalid");
}
}
.invalid {
background-color: rgba(255,0,0,.7);
color: white;
}
.invalid::placeholder {
color: white;
}
<input type="text" placeholder="Type Something..." id="input">
<button onclick="check();">Check</button>

How to validate without allowing gmail and yahoo while user signing up?

How to Validate? Don’t allow Gmail, Yahoo, etc email addresses. And one more issue is that when all the fields are not entered submit should be disabled. when i fill all submit is enabled and when i remove one input after filling it, submit should be disabled, but still it's enabled. How to fix that?
$("#passwordv").on("focusout", function (e) {
if ($(this).val() != $("#passwordvConfirm").val()) {
$("#passwordvConfirm").removeClass("valid").addClass("invalid");
$('#btn-1').show();
} else {
$("#passwordvConfirm").removeClass("invalid").addClass("valid");
$('#btn').removeAttr("disabled");
$('#btn-1').hide();
}
});
$("#passwordvConfirm").on("keyup", function (e) {
if ($("#passwordv").val() != $(this).val()) {
$(this).removeClass("valid").addClass("invalid");
$('#btn-1').show();
} else {
$(this).removeClass("invalid").addClass("valid");
$('#btn').removeAttr("disabled");
$('#btn-1').hide();
}
});
$(document).ready(function () {
$('#passwordv').keyup(function () {
$('#result').html(checkStrength($('#passwordv').val()))
})
function checkStrength(password) {
var strength = 0
if (password.length < 6) {
$('#result').removeClass()
$('#result').addClass('short')
return 'Too short'
}
if (password.length > 7) strength += 1
// If password contains both lower and uppercase characters, increase strength value.
if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) strength += 1
// If it has numbers and characters, increase strength value.
if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/)) strength += 1
// If it has one special character, increase strength value.
if (password.match(/([!,%,&,#,#,$,^,*,?,_,~])/)) strength += 1
// If it has two special characters, increase strength value.
if (password.match(/(.*[!,%,&,#,#,$,^,*,?,_,~].*[!,%,&,#,#,$,^,*,?,_,~])/)) strength += 1
// Calculated strength value, we can return messages
// If value is less than 2
if (strength < 2) {
$('#result').removeClass()
$('#result').addClass('weak')
return 'Weak'
} else if (strength == 2) {
$('#result').removeClass()
$('#result').addClass('good')
return 'Good'
} else {
$('#result').removeClass()
$('#result').addClass('strong')
return 'Strong'
}
}
});
$('.form').find('input, textarea').on('keyup blur focus', function (e) {
var $this = $(this),
label = $this.prev('label');
if (e.type === 'keyup') {
if ($this.val() === '') {
label.removeClass('active highlight');
} else {
label.addClass('active highlight');
}
} else if (e.type === 'blur') {
if ($this.val() === '') {
label.removeClass('active highlight');
} else {
label.removeClass('highlight');
}
} else if (e.type === 'focus') {
if ($this.val() === '') {
label.removeClass('highlight');
} else if ($this.val() !== '') {
label.addClass('highlight');
}
}
});
$('.tab a').on('click', function (e) {
e.preventDefault();
$(this).parent().addClass('active');
$(this).parent().siblings().removeClass('active');
target = $(this).attr('href');
$('.tab-content > div').not(target).hide();
$(target).fadeIn(600);
});
*,
*:before,
*:after {
box-sizing: border-box;
}
html {
overflow-y: scroll;
}
body {
background: #f1f0ee;
font-family: 'Titillium Web', sans-serif;
}
a {
text-decoration: none;
color: #1ab188;
transition: .5s ease;
}
a:hover {
color: #179b77;
}
.form {
background: rgba(19, 35, 47, 0.9);
padding: 40px;
max-width: 600px;
margin: 130px auto;
border-radius: 4px;
box-shadow: 0 4px 10px 4px rgba(19, 35, 47, 0.3);
}
#media only screen and (max-width: 768px) {
.form {
background: rgba(19, 35, 47, 0.9);
padding: 40px;
max-width: 600px;
margin: 30px auto;
border-radius: 4px;
box-shadow: 0 4px 10px 4px rgba(19, 35, 47, 0.3);
}
}
.tab-group {
list-style: none;
padding: 0;
margin: 0 0 40px 0;
}
.tab-group:after {
content: "";
display: table;
clear: both;
}
.tab-group li a {
display: block;
text-decoration: none;
padding: 15px;
background: rgba(160, 179, 176, 0.25);
color: #a0b3b0;
font-size: 20px;
float: left;
width: 50%;
text-align: center;
cursor: pointer;
transition: .5s ease;
}
.tab-group li a:hover {
background: #179b77;
color: #ffffff;
}
.tab-group .active a {
background: #1ab188;
color: #ffffff;
}
.tab-content>div:last-child {
display: none;
}
h1 {
text-align: center;
color: #ffffff !important;
font-weight: 300;
margin: 0 0 40px !important;
}
label {
position: absolute;
-webkit-transform: translateY(6px);
transform: translateY(6px);
left: 13px;
color: rgba(255, 255, 255, 0.5);
transition: all 0.25s ease;
-webkit-backface-visibility: hidden;
pointer-events: none;
margin-top: 18px;
}
label .req {
margin: 2px;
color: #1ab188;
}
label.active {
-webkit-transform: translateY(-25px);
transform: translateY(-25px);
left: 2px;
font-size: 14px;
}
label.active .req {
opacity: 0;
}
label.highlight {
color: #ffffff;
}
input,
textarea {
font-size: 22px;
display: block;
width: 100%;
height: 100%;
padding: 8px 10px;
background: none;
background-image: none;
border: 1px solid #a0b3b0;
color: #ffffff;
border-radius: 0;
transition: border-color .25s ease, box-shadow .25s ease;
}
input:focus,
textarea:focus {
outline: 0;
border-color: #1ab188;
}
textarea {
border: 2px solid #a0b3b0;
resize: vertical;
}
.field-wrap {
position: relative;
margin-bottom: 25px;
}
.top-row:after {
content: "";
display: table;
clear: both;
}
.top-row>div {
float: left;
width: 48%;
margin-right: 4%;
}
.top-row>div:last-child {
margin: 0;
}
.button {
border: 0;
outline: none;
border-radius: 50px;
padding: 15px 0;
font-size: 20px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: .1em;
background: #1ab188;
color: #ffffff;
transition: all 0.5s ease;
-webkit-appearance: none;
}
.button:hover,
.button:focus {
background: #179b77;
}
.button-block {
display: block;
width: 50%;
margin: 0 auto;
}
.forgot {
text-align: right;
}
#toast-container {
top: 4% !important;
right: 40% !important;
left: 40%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<div class="form">
<ul class="tab-group">
<li class="tab active">Log In</li>
<li class="tab">Sign Up</li>
</ul>
<div class="tab-content">
<div id="login">
<form id="form_id" method="post" name="myform">
<div class="field-wrap">
<label>
User Name<span class="req">*</span>
</label>
<input type="text" autocomplete="off" name="username" id="username" required>
</div>
<div class="field-wrap">
<label>
Password<span class="req">*</span>
</label>
<input type="password" autocomplete="off" name="password" id="password" required>
</div>
<p class="forgot">Forgot Password?</p>
<input type="button" value="Log in" id="submit" onclick="validate()" class="button button-block">
</form>
</div>
<div id="signup">
<form>
<div class="field-wrap">
<label>
Name<span class="req">*</span>
</label>
<input type="text" required autocomplete="off" />
</div>
<div class="field-wrap">
<label>
Email Address<span class="req">*</span>
</label>
<input type="email" required autocomplete="off" />
</div>
<div class="field-wrap">
<label>
Company Details<span class="req">*</span>
</label>
<input type="text" required autocomplete="off" />
</div>
<div class="field-wrap">
<label for="passwordv">
Set A Password<span class="req">*</span>
</label>
<input id="passwordv" type="password" class="validate" required autocomplete="off" />
<span id="result" style="color: white;"></span>
</div>
<div class="field-wrap" style="margin-bottom: 0px">
<label id="lblPasswordvConfirm" for="passwordvConfirm" data-error="Password not match"
data-success="Password Match">
Confirm Password<span class="req">*</span>
</label>
<input id="passwordvConfirm" type="password" required autocomplete="off" />
</div>
<label class="field-wrap" id="btn-1" style="display: none;color: white;font-size: 15px">password
didn't match
</label>
<input type="submit" value="submit" id="btn" class="button button-block" style="margin-top:20px;cursor:not-allowed"
disabled />
</form>
</div>
</div><!-- tab-content -->
</div> <!-- /form -->
Okay, so I broke down your code a bit to make it more easily understood. This example will only include your signup part of your application.
As I explained in my comment, what you could do to test the E-mails to see whether they are a Gmail or a Yahoo E-mail, is by using regular expressions (RegExp).
Example of Gmail RegExp:
/([a-zA-Z0-9]+)([\.{1}])?([a-zA-Z0-9]+)\#gmail([\.])com/g
Example of Yahoo RegExp:
/^[^#]+#(yahoo|ymail|rocketmail)\.(com|in|co\.uk)$/i
In my example, I'll put them into functions for simplicity.
Gmail RegExp function:
function regExpGmail() {
return RegExp(/([a-zA-Z0-9]+)([\.{1}])?([a-zA-Z0-9]+)\#gmail([\.])com/g);
}
Yahoo RegExp function:
function regExpYahoo() {
return RegExp(/^[^#]+#(yahoo|ymail|rocketmail)\.(com|in|co\.uk)$/i);
}
Now, I altered some of your code a bit in order to have some selectors to go by. Some of your input fields did not contain any selectors, such as name or id, while others did. So I took the liberty to add some.
One thing to note, is that the id you assigned your password input field (not the password confirm one, but the one before that) had some id conflicts. Therefore I took the liberty to change the id accordingly.
I then made a function handling all the validation logic of the input fields to fit your needs in your question. However, again, pretty simplified. I would suggest you alter it to fit your solution a little bit better, but it should give you more than a general idea.
Full Example:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script>
function regExpGmail() {
return RegExp(/([a-zA-Z0-9]+)([\.{1}])?([a-zA-Z0-9]+)\#gmail([\.])com/g);
}
function regExpYahoo() {
return RegExp(/^[^#]+#(yahoo|ymail|rocketmail)\.(com|in|co\.uk)$/i);
}
function validateInputs() {
reGmail=regExpGmail();
reYahoo=regExpYahoo();
var result = true;
var nameCheck=$('#nameField').val();
var emailCheck=$('#emailField').val();
var compDetailsCheck=$('#compDetailsField').val();
var passwordCheck=$('#passwordvz').val();
var passwordConfirmCheck=$('#passwordvConfirm').val();
if(!nameCheck) {
result=false;
$('#nameError').html('Name is missing!');
}
else {
$('#nameError').html('');
}
if(!emailCheck) {
result=false;
$('#emailError').html('E-mail is missing!');
}
else if(reGmail.test(emailCheck)) {
result=false;
$('#emailError').html('Gmail is not allowed!');
}
else if(reYahoo.test(emailCheck)) {
result=false;
$('#emailError').html('Yahoo is not allowed!');
}
else {
$('#emailError').html('');
}
if(!compDetailsCheck) {
result=false;
$('#compDetailsError').html('Company Details is missing!');
}
else {
$('#compDetailsError').html('');
}
if(!passwordCheck) {
result=false;
$('#passwordError').html('Password is missing!');
}
else {
$('#passwordError').html('');
}
if(passwordCheck != passwordConfirmCheck) {
result=false;
$('#passwordError2').html('The passwords do not match!');
}
else {
$('#passwordError2').html('');
}
if(result == true) {
$('#btn').removeAttr('disabled');
$('#btn').css("cursor", "");
alert('Everything ok, you may now press the submit button!');
}
}
</script>
<div class="form">
<div class="tab-content">
<div id="signup">
<form>
<div class="field-wrap">
<span id="nameError" style="color: red !important;"></span><br />
<label>
Name<span class="req">*</span>
</label>
<input type="text" id="nameField" required autocomplete="off" onkeyup="validateInputs();" /><br />
</div>
<div class="field-wrap">
<span id="emailError" style="color: red !important;"></span><br />
<label>
Email Address<span class="req">*</span>
</label>
<input type="email" id="emailField" required autocomplete="off" onkeyup="validateInputs();" /><br />
</div>
<div class="field-wrap">
<span id="compDetailsError" style="color: red !important;"></span><br />
<label>
Company Details<span class="req">*</span>
</label>
<input type="text" id="compDetailsField" required autocomplete="off" onkeyup="validateInputs();" /><br />
</div>
<div class="field-wrap">
<span id="passwordError" style="color: red !important;"></span><br />
<label for="passwordv">
Set A Password<span class="req">*</span>
</label>
<input id="passwordvz" type="password" class="validate" required autocomplete="off" onkeyup="validateInputs();" /><br />
</div>
<div class="field-wrap" style="margin-bottom: 0px">
<span id="passwordError2" style="color: red !important;"></span><br />
<label id="lblPasswordvConfirm" for="passwordvConfirm" data-error="Password not match"
data-success="Password Match">
Confirm Password<span class="req">*</span>
</label>
<input id="passwordvConfirm" type="password" required autocomplete="off" onkeyup="validateInputs();" /><br />
</div>
<input type="submit" value="submit" id="btn" class="button button-block" style="margin-top:20px;cursor:not-allowed" disabled />
</form>
</div>
</div><!-- tab-content -->
</div> <!-- /form -->
Screenshots of the validation process:

Login validation function

I have been trying to get this to work for a while now. I cannot connect the login function to the form.
I have tried onsubmit on both the form tag and the button input tag, i have tried onclick but it does not get the code from js function.
index1.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Google maps</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<!--<link rel="http://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="util.js"></script>
<script src="JavaScript.js"></script>
<script type="text/javascript"></script>
<style>
#container {
width: 1200px;
}
#map {
width: 80%;
min-height: 600px;
/*float: right;*/
margin-top: 15px;
margin-left: auto;
margin-right: auto;
}
#img {
width: 150px;
height: 150px;
float: left;
margin-top: auto;
}
/*sökruta*/
#searchBox {
background-color: #ffffff;
padding: 5px;
font-family: 'Roboto','sans-serif';
margin-bottom: 10px;
float: top;
}
/*
html, body {
height: 100%;
margin: 0;
padding: 0;
}
*/
.search-form .form-group {
float: right !important;
transition: all 0.35s, border-radius 0s;
width: 32px;
height: 32px;
background-color: #fff;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075) inset;
border-radius: 25px;
border: 1px solid #ccc;
}
.search-form .form-group input.form-control {
padding-right: 20px;
border: 0 none;
background: transparent;
box-shadow: none;
display:block;
}
.search-form .form-group input.form-control::-webkit-input-placeholder {
display: none;
}
.search-form .form-group input.form-control:-moz-placeholder {
/* Firefox 18- */
display: none;
}
.search-form .form-group input.form-control::-moz-placeholder {
/* Firefox 19+ */
display: none;
}
.search-form .form-group input.form-control:-ms-input-placeholder {
display: none;
}
.search-form .form-group:hover,
.search-form .form-group.hover {
width: 100%;
border-radius: 4px 25px 25px 4px;
}
.search-form .form-group span.form-control-feedback {
position: absolute;
top: -1px;
right: -2px;
z-index: 2;
display: block;
width: 34px;
height: 34px;
line-height: 34px;
text-align: center;
color: #3596e0;
left: initial;
font-size: 14px;
}
.form-group {
max-width: 300px;
margin-right: auto;
margin-left: auto;
}
</style>
</head>
<body id="container">
<img id="img" src="http://www2.math.su.se/icsim/images/sterik.jpg" alt="Stockholm"/>
<div class="row">
<br>
<div class="col-md-4 col-md-offset-3">
<form action="" class="search-form">
<div class="form-group has-feedback">
<label id="Search" class="sr-only">Search</label>
<input type="text" class="form-control" name="search" id="searchField" placeholder="Sök">
<span class="glyphicon glyphicon-search form-control-feedback"></span>
</div>
</form>
</div>
<div class="form-group">
<form id="loginForm" name="loginForm" method="POST">
<label for="user">Användarnamn: </label>
<br>
<input class="form-control" type="text" id="user" name="user" required>
<br>
<label for="password">Lösenord: </label>
<br>
<input class="form-control" type="password" id="password" name="passwords" required>
<br>
<br>
<input class="form-control" type="submit" id="login" value="Logga in" onclick="login()">
</form>
</div>
<div id="map">
</div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDNPkC40KP9lMKHUsJW7q403qnwRqYkTno&callback=initMap">
</script>
</div>
</body>
JavaScript.js
function login() {
//spara username och password i två varibler med samma namn från formet.
var username = document.getElementById("user").value;
var password = document.getElementById("password").value;
if(username === "admin"
&& password === "123" )
{
alert( "validation succeeded" );
location.href="adminView.php";
}
else
{
alert( "validation failed" );
location.href="index1.html";
}
}
I have created working JSFiddle - Please Check : https://jsfiddle.net/5w6fg52m/1/
Below Code working fine :
<script>
//just change function name as it's conflict with button id
function login1() {
//spara username och password i två varibler med samma namn från formet.
var username = document.getElementById("user").value;
var password = document.getElementById("password").value;
if(username === "admin"
&& password === "123" )
{
alert( "validation succeeded" );
location.href="adminView.php";
}
else
{
alert( "validation failed" );
location.href="index1.html";
}
return false;
}
</script>
//HTML
<div class="form-group">
<form id="loginForm" name="loginForm" method="POST">
<label for="user">Användarnamn: </label>
<br>
<input class="form-control" type="text" id="user" name="user" required>
<br>
<label for="password">Lösenord: </label>
<br>
<input class="form-control" type="password" id="password" name="passwords" required>
<br>
<br>
<input class="form-control" type="button" id="login" value="Logga in" onclick="return login1();">
</form>
</div>
-> I have created other version of JSFiddle, so you come to know conflict issue easily: https://jsfiddle.net/5w6fg52m/2/
Here i have keep function name same(login) and change ID of submit button.
You can set the submit event directly to your like
document.getElementById("loginForm").onsubmit = function() { ... };
Bellow a sample snippet :
window.onload = function(){
document.getElementById("loginForm").onsubmit = function() {
//spara username och password i två varibler med samma namn från formet.
var username = document.getElementById("user").value;
var password = document.getElementById("password").value;
if (username === "admin" &&
password === "123") {
alert("validation succeeded");
//location.href = "adminView.php";
} else {
alert("validation failed");
//location.href = "index1.html";
}
// to prevent submit
return false;
}
}
<div class="form-group">
<form id="loginForm" name="loginForm" method="POST">
<label for="user">Användarnamn: </label>
<br>
<input class="form-control" type="text" id="user" name="user" required>
<br>
<label for="password">Lösenord: </label>
<br>
<input class="form-control" type="password" id="password" name="passwords" required>
<br>
<br>
<input class="form-control" type="submit" id="login" value="Logga in">
</form>
</div>
This happens when you declare variable or function with the same name as declare before. just rename login function or rename id="login".

Categories