I am trying to make the border of a textbox red when a text that does not containthe "#" is typed in (it is an email checker). Unfortunately, this does not happen.
I have tried to use a class that contains the new border color but unfortunately, it seems that this change is never applied.
This is the html and js code:
<!DOCTYPE html>
<html>
<head>
<title>
Sign Up Page
</title>
<link rel="stylesheet" href="style.css" media="screen"/>
</head>
<body>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("something must be filled out");
return false;
}
else if (!(x.includes("#")))
{
alert("you must have to filled value with #");
document.getElementById("nameT").style.color="red";
document.getElementById("fname").className = 'error';
return false;
}
}
</script>
<div class="ocean">
<div class="wave"></div>
<div class="wave"></div>
</div>
<h1>
<center>
Whale
</center>
</h1>
<div class="loginbox">
<h2>
Login
</h2>
<form name="myForm" onsubmit="return validateForm()"
method="post">
<p id="nameT"> email </p>
<input type="text" name="fname" placeholder="enter
email" onblur="validateForm()">
<p name="passT"> password </p>
<input type="text" name="name" placeholder="enter
password">
<br>
<input type="submit" value="Submit">
<br>
<a href="#">
Lost your password?
</a>
<br>
<a href="#">
Create an account
</a>
</form>
</div>
</body>
</html>
This is the css code:
html, body { height: 100%; }
body {
background:radial-gradient(ellipse at center, rgba(255,254,234,1)
0%, rgba(255,254,234,1) 35%, #ffffff 100%);
overflow: hidden;
}
.ocean {
height: 5%;
width:100%;
position:absolute;
bottom:0;
left:0;
background: #ffffff;
}
.wave {
background: url(https://s3-us-west-
2.amazonaws.com/s.cdpn.io/85486/wave.svg) repeat-x;
position: absolute;
top: -198px;
width: 6400px;
height: 198px;
animation: wave 7s cubic-bezier( 0.36, 0.45, 0.63, 0.53)
infinite;
transform: translate3d(0, 0, 0);
}
.wave:nth-of-type(2) {
top: -175px;
animation: wave 7s cubic-bezier( 0.36, 0.45, 0.63, 0.53) -.125s
infinite, swell 7s ease -1.25s infinite;
opacity: 1;
}
#keyframes wave {
0% {
margin-left: 0;
}
100% {
margin-left: -1600px;
}
}
#keyframes swell {
0%, 100% {
transform: translate3d(0,-25px,0);
}
50% {
transform: translate3d(0,5px,0);
}
}
.loginbox
{
width: 340px;
height: 360px;
background: #000;
color: #fff;
top: 50%;
left:50%;
position: absolute;
transform: translate(-50%, -50%);
box-sizing: border-box;
}
h2
{
margin: 0;
padding: 0 0 20px;
text-align: center;
font-size: 22px;
}
.loginbox input
{
width: 100%;
margin-bottom: 20px;
}
.loginbox input[type="text"], input[type="password"]
{
border: none;
border-bottom: 1px solid #fff;
background: transparent;
outline: none;
height: 40px;
color: #fff;
font-size: 16px;
}
.loginbox input[type="submit"]
{
border: none;
outline: none;
height: 48px;
background: #fb2525;
color: #fff;
font-size: 18px;
border-radius: 20px;
}
.loginbox input[type="submit"]:hover
{
cursor: pointer;
background: #ffc107;
color: #000;
}
.loginbox a
{
text-decoration: none;
font-size: 12px;
line-height: 20px;
color: darkgrey;
}
.loginbox p
{
margin: 0;
padding: 10px;
font-weight: bold;
}
.loginbox a:hover
{
color: #ffc107;
}
.error{
border:2px solid red;
}
The expected output is the border becoming red if the "#" symbol is not typed into the email textbox. The actual result is no such effect and instead, a "cannot set property 'className' of null" error.
You are using the document.getElementById("fname") but you do not have any id which has name "fname" so update input as,
<input type="text" id="fname" name="fname" placeholder="enter
email" onblur="validateForm()">
Change the getElementById to,
document.getElementById("fname").classList.add('error');
and change your .error class to,
.error{
border-bottom:2px solid red !important;
}
Try it by accessing elements via document.forms as below
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("something must be filled out");
return false;
} else if (!(x.includes("#"))) {
alert("you must have to filled value with #");
document.forms.myForm.name.style.color = "red";
document.forms.myForm.name.style.border = "1px solid red";
document.forms.myForm.fname.className = 'error';
return false;
} else {
document.forms.myForm.name.style.color = "#000";
document.forms.myForm.name.style.border = "1px solid #000";
}
}
<div class="ocean">
<div class="wave"></div>
<div class="wave"></div>
</div>
<h1>
<center>
Whale
</center>
</h1>
<div class="loginbox">
<h2>
Login
</h2>
<form name="myForm" onsubmit="return validateForm()" method="post">
<p id="nameT"> email </p>
<input type="text" name="fname" placeholder="enter
email" onblur="validateForm()">
<p name="passT"> password </p>
<input type="text" name="name" placeholder="enter
password">
<br>
<input type="submit" value="Submit">
<br>
<a href="#">
Lost your password?
</a>
<br>
<a href="#">
Create an account
</a>
</form>
</div>
just add id=fname in your text field and replace your js with my js
<input type="text" id="fname" name="fname" placeholder="enter email"
onblur="validateForm()">
Here is js
function validateForm() {
document.getElementById("nameT").style.color = "white";
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("something must be filled out");
return false;
} else if (!(x.includes("#"))) {
alert("you must have to filled value with #");
document.getElementById("nameT").style.color = "red";
document.getElementById("fname").className = 'error';
return false;
}
}
here is demo on jsbin
Related
<html>
<script>
function passwordvalidation() #validate if password is strong and if botth passwords are equal
{
var x=document.forms["signup"]["psw"].value;
var y=document.form["signup"]["psw-repeat"].value;
var z=document.form["signup"]["email"].value;
alert(x);
if (x == ""||y==""||z=="") {
alert("form must be filled out");
return false;
}
else if(y!=x)
{
alert("password does not match");
return false;
}
else if (!(x.match(/[a-z]/g) && x.match(
/[A-Z]/g) && x.match(
/[0-9]/g) && x.match(
/[^a-zA-Z\d]/g) && x.length >= 8))
{
alert("weak password")
return false;
}
else
{
return true;
}
}
</script>
<style>
body {font-family: Arial, Helvetica, sans-serif;}
* {box-sizing: border-box}
/* Full-width input fields */
input[type=text], input[type=password] {
width: 100%;
padding: 15px;
margin: 5px 0 22px 0;
display: inline-block;
border: none;
background: #f1f1f1;
}
input[type=text]:focus, input[type=password]:focus {
background-color: #ddd;
outline: none;
}
hr {
border: 1px solid #f1f1f1;
margin-bottom: 25px;
}
/* Set a style for all buttons */
button {
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
opacity: 0.9;
}
button:hover {
opacity:1;
}
/* Extra styles for the cancel button */
.cancelbtn {
padding: 14px 20px;
background-color: #f44336;
}
/* Float cancel and signup buttons and add an equal width */
.cancelbtn, .signupbtn {
float: left;
width: 50%;
}
/* Add padding to container elements */
.container {
padding: 16px;
}
/* Clear floats */
.clearfix::after {
content: "";
clear: both;
display: table;
}
/* Change styles for cancel button and signup button on extra small screens */
#media screen and (max-width: 300px) {
.cancelbtn, .signupbtn {
width: 100%;
}
}
</style>
<body>
<form name="signup" action="/login" onsubmit="return passwordvalidation()" style="border:1px solid #ccc">
<div class="container">
<h1>Sign Up</h1>
<h6>Please fill in this form to create an account.</h6>
<p>Strong password must contain 8 characters </p>
<hr>
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<label for="psw-repeat"><b>Repeat Password</b></label>
<input type="password" placeholder="Repeat Password" name="psw-repeat" required>
<div class="clearfix">
<button type="submit" class="signupbtn">Sign Up</button>
</div>
</div>
</form>
</body>
</html>
You have several errors in these lines:
var x=document.forms["signup"]["psw"].value;
var y=document.form["signup"]["psw-repeat"].value;
var z=document.form["signup"]["email"].value;
You can use many methods to retrieve the inputs values, but this way is throwing errors. Check how to do it by using document.getElementBy*** or similar
It is calling the validation function, but you made a spelling mistake in second and third line. Correct
document.form --> document.forms document.form is undefined and your function is exiting with TypeError when you call document.form["signup"] without returning false, and thus your form is navigating to defined action
function passwordvalidation(form)
{
var x=form["psw"].value;
var y=form["psw-repeat"].value;
var z=form["email"].value;
if (x == ""||y==""||z=="") {
alert("form must be filled out");
console.log("form must be filled out");
return false;
}
else if(y!=x)
{
alert("password does not match");
return false;
}
else if (!(x.match(/[a-z]/g) && x.match(
/[A-Z]/g) && x.match(
/[0-9]/g) && x.match(
/[^a-zA-Z\d]/g) && x.length >= 8))
{
alert("weak password")
return false;
}
else
{
return true;
}
}
body {font-family: Arial, Helvetica, sans-serif;}
* {box-sizing: border-box}
/* Full-width input fields */
input[type=text], input[type=password] {
width: 100%;
padding: 15px;
margin: 5px 0 22px 0;
display: inline-block;
border: none;
background: #f1f1f1;
}
input[type=text]:focus, input[type=password]:focus {
background-color: #ddd;
outline: none;
}
hr {
border: 1px solid #f1f1f1;
margin-bottom: 25px;
}
/* Set a style for all buttons */
button {
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
opacity: 0.9;
}
button:hover {
opacity:1;
}
/* Extra styles for the cancel button */
.cancelbtn {
padding: 14px 20px;
background-color: #f44336;
}
/* Float cancel and signup buttons and add an equal width */
.cancelbtn, .signupbtn {
float: left;
width: 50%;
}
/* Add padding to container elements */
.container {
padding: 16px;
}
/* Clear floats */
.clearfix::after {
content: "";
clear: both;
display: table;
}
/* Change styles for cancel button and signup button on extra small screens */
#media screen and (max-width: 300px) {
.cancelbtn, .signupbtn {
width: 100%;
}
}
<form name="signup" action="/login" onsubmit="return passwordvalidation(this)" style="border:1px solid #ccc">
<div class="container">
<h1>Sign Up</h1>
<h6>Please fill in this form to create an account.</h6>
<p>Strong password must contain 8 characters </p>
<hr>
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<label for="psw-repeat"><b>Repeat Password</b></label>
<input type="password" placeholder="Repeat Password" name="psw-repeat" required>
<div class="clearfix">
<button type="submit"class="signupbtn">Sign Up</button>
</div>
</div>
</form>
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? 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:
I'm new to HTML/CSS/JS.
I have an HTML form with two input fields: e-mail and favorite website. I have two regular expressions in my JS file which check the input. This works fine, but I want to trigger an error message when the user clicks out of the box(onblur event).
My problem is that I want to apply a transition effect on the error, so it becomes visible over time, not just suddenly appears. Plus, right now, the error message pops up only once.
So my questions are:
How to apply the transition effect on the error message;
How to make it appear as many times as the user fails to enter the right input.
Here is my the HTML file :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="CSS2_2.css">
</head>
<body>
<div id="webpagevalidationerror" class="error">
<span class="closebtn" onclick="this.parentElement.style.display='none';">×</span>
<p>Wrong website !</p>
</div>
<div id="emailvalidationerror" class="error">
<span class="closebtn" onclick="this.parentElement.style.display='none';">×</span>
<p>Wrong e-mail !</p>
</div>
<form name="myform" class = "relative">
<fieldset>
<legend>Personal information:</legend>
E-mail :<br>
<input id="email" type="text" name="email" onblur="validateEmail(this)"><br>
Favorite website :<br>
<input id="webpage" type="text" name="webpage" onblur="validateWebpage(this)"><br><br>
<input id="submit" type="submit" value="Submit">
</fieldset>
</form>
<script src="JS_2.js"></script>
</body>
And the CSS file :
fieldset {
display: inline;
}
form.relative {
position: relative;
left: 150px;
top: 150px;
}
p {
position: relative;
left: 30px;
top: 16px;
width: 150px;
}
div {
position: relative;
left: 120px;
top: 130px;
width: 250px;
height: 50px;
background-color: #f44336;
color: white;
display: none;
/*transition: 2s; How to apply this transition for the .triggered attributes ?
transition-timing-function: linear;*/
}
.triggered {
display: block;
}
.closebtn {
margin-right: 25px;
margin-top: 13px;
color: white;
font-weight: bold;
float: right;
font-size: 22px;
cursor: pointer;
transition: 0.3s;
}
.closebtn:hover {
color: black;
}
And the Javascript file :
var emailerror = document.getElementById("emailvalidationerror");
var webpageerror = document.getElementById("webpagevalidationerror");
function validateEmail(email) {
var re = new RegExp("^[^#]+#yahoo.com$");
var re2 = new RegExp("^[^#]+#gmail.com$");
if (!(re.test(email.value)) && !(re2.test(email.value)) || email.value == "") {
emailerror.classList.toggle("triggered");
}
}
function validateWebpage(webpage) {
var re = new RegExp("^www\\.[a-zA-Z0-9_-]+\\.[a-z]+\\.[a-z]+$");
if (!(re.test(webpage.value)) || webpage.value == "") {
webpageerror.classList.toggle("triggered");
}
}
You can't animate from display:none to display:block. The trick is to set scale and opacity to 0, then trigger the opacity animation with the delay of the scale animation duration.
Also validation functions may return a boolean, to check if everything is ok when you submit your form (and you don't want to toggle triggered class, as you wish the message to be still displayed as long as the input is wrong. So just add class if it's wrong, remove it if it's ok).
And rather than set inline atributes on your HTML elements (onClick,onBlur,...), set eventlisteners in your js code (to avoid to mix js and html)
Here a working snippet adapted from your existing code:
var emailerror = document.getElementById("emailvalidationerror");
var webpageerror = document.getElementById("webpagevalidationerror");
var closeBtn = document.getElementsByClassName("closebtn");
// loop throught closeBtn nodelist to add listener for each buttons
for(var i = 0; i < closeBtn.length; i++)
{
closeBtn[i].addEventListener("click",function(e){
e.currentTarget.parentElement.classList.remove("triggered");
});
}
document.getElementById("webpage").addEventListener("blur",validateWebpage);
document.getElementById("email").addEventListener("blur",validateEmail);
document.getElementById("submit").addEventListener("click",submitForm);
function validateEmail() {
var valToTest = document.getElementById("email").value;
var re = new RegExp("^[^#]+#yahoo.com$");
var re2 = new RegExp("^[^#]+#gmail.com$");
if (!(re.test(valToTest)) && !(re2.test(valToTest)) || valToTest == "") {
emailerror.classList.add("triggered");
return false;
}
emailerror.classList.remove("triggered");
return true;
}
function validateWebpage() {
var valToTest = document.getElementById("webpage").value;
var re = new RegExp("^www\\.[a-zA-Z0-9_-]+\\.[a-z]+\\.[a-z]+$");
if (!(re.test(valToTest)) || valToTest == "") {
webpageerror.classList.add("triggered");
return false;
}
webpageerror.classList.remove("triggered");
return true;
}
function submitForm(e){
e.preventDefault();
var emailOk = validateEmail();
var webPageOk = validateWebpage();
if(emailOk && webPageOk){
document.getElementById("myform").submit();
}
}
fieldset {
display: inline;
}
form.relative {
position: relative;
left: 150px;
top: 150px;
}
p {
position: relative;
left: 30px;
top: 16px;
width: 150px;
}
div {
position: relative;
left: 120px;
top: 130px;
width: 250px;
height: 50px;
background-color: #f44336;
color: white;
/* display: none;*/
/*transition: 2s; How to apply this transition for the .triggered attributes ?
transition-timing-function: linear;*/
transform-origin:50% 50%;
transform:scale(0);
opacity:0;
transition: transform .2s, opacity 2s .2s;
}
.triggered {
/* display: block;*/
transform:scale(1);
opacity:1;
}
.closebtn {
margin-right: 25px;
margin-top: 13px;
color: white;
font-weight: bold;
float: right;
font-size: 22px;
cursor: pointer;
transition: 0.3s;
}
.closebtn:hover {
color: black;
}
<div id="webpagevalidationerror" class="error">
<span class="closebtn">×</span>
<p>Wrong website !</p>
</div>
<div id="emailvalidationerror" class="error">
<span class="closebtn">×</span>
<p>Wrong e-mail !</p>
</div>
<form id="myform" class = "relative">
<fieldset>
<legend>Personal information:</legend>
E-mail :<br>
<input id="email" type="text" name="email"><br>
Favorite website :<br>
<input id="webpage" type="text" name="webpage"><br><br>
<input id="submit" type="submit" value="Submit">
</fieldset>
</form>
If you just want to show it smoothly just change your triggered class
This will add a transition effect while adding the class to display it.
https://jsfiddle.net/ycLn2fyb/25/
HTML and javascript
<div id="webpagevalidationerror" class="error">
<span class="closebtn" >×</span>
<p>Wrong website !</p>
</div>
<button onClick="myFunction()"> TEST BUTTON</button>
<script type="text/javascript">
var webpageerror = document.getElementById("webpagevalidationerror");
function myFunction()
{
webpageerror.classList.toggle("show");
}
</script>
Css:
div {
position: relative;
left: 120px;
top: 130px;
width: 250px;
height: 50px;
background-color: #f44336;
color: white;
opacity: 0;
}
.show {
opacity: 1;
transition: opacity 2s ease-in;
-moz-transition: opacity 2s ease-in;
-webkit-transition: opacity 2s ease-in;
}
p {
position: relative;
left: 30px;
top: 16px;
width: 150px;
}
.closebtn {
margin-right: 25px;
margin-top: 13px;
color: white;
font-weight: bold;
float: right;
font-size: 22px;
cursor: pointer;
transition: 0.3s;
}
.closebtn:hover {
color: black;
}
I'm very new to Javascript. I have done one template for login, It is working like a charm. Here My question is how to set up the validation and navigation like if(username==root && password==root) then it should redirect into other page. I just post my code. I didn't include the css code. Then i did this code in html in that i have try to write the javascript but i don't know how to handle this.
My code:
<!DOCTYPE html>
<html>
<style>
/* Full-width input fields */
input[type=text], input[type=password] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;
}
/* Set a style for all buttons */
button {
background-color: #0077B5;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
}
button:hover {
opacity: 0.8;
}
/* Extra styles for the cancel button */
.cancelbtn {
width: auto;
padding: 10px 18px;
background-color: #f44336;
}
/* Center the image and position the close button */
.imgcontainer {
text-align: center;
margin: 10px 0 5px 0;
position: relative;
}
img.cisco{
width: 30%;
border-radius: 30%;
}
.container {
padding: 10px;
}
span.psw {
float: right;
padding-top: 16px;
}
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
/*overflow: auto; Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
padding-top: 5px;
}
/* Modal Content/Box */
.modal-content {
background-color: #fefefe;
margin: 5% auto 15% auto; /* 5% from the top, 15% from the bottom and centered */
border: 1px solid #888;
width: 80%; /* Could be more or less, depending on screen size */
}
/* The Close Button (x) */
.close {
position: absolute;
right: 25px;
top: 0;
color: #000;
font-size: 35px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: red;
cursor: pointer;
}
/* Add Zoom Animation */
.animate {
-webkit-animation: animatezoom 0.6s;
animation: animatezoom 0.6s
}
#-webkit-keyframes animatezoom {
from {-webkit-transform: scale(0)}
to {-webkit-transform: scale(1)}
}
#keyframes animatezoom {
from {transform: scale(0)}
to {transform: scale(1)}
}
/* Change styles for span and cancel button on extra small screens */
#media screen and (max-width: 200px) {
span.psw {
display: block;
float: none;
}
.cancelbtn {
width: 100%;
}
.Center {
display: flex;
align-items: center;
justify-content: center;
}
}
</style>
<body>
<h2><text-align:center>Authentication Required</h2>
<button onclick="document.getElementById('id01').style.display='block'">Login</button>
<div id="id01" class="modal">
<form class="modal-content animate" method="post" name="myform">
<div class="imgcontainer">
<span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">×</span>
<img src="../images/cisco1.png" alt="Cisco" class="cisco">
</div>
<div class="container">
<label><b>Username</b></label>
<input type="text" id="username" placeholder="Enter Username" name="uname" required>
<label><b>Password</b></label>
<input type="password" id="password" placeholder="Enter Password" name="psw" required>
<button type="submit" id="login" onclick="validate()">Login</button>
<input type="checkbox" checked="checked"> Remember me
</div>
<div class="container" style="background-color:#f1f1f1">
<button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>
<span class="psw">Forgot password?</span>
</div>
</form>
</div>
<script>
var attempt = 3; //Variable to count number of attempts
//Below function Executes on click of login button
function validate(){
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if ( username == "root" && password == "root"){
alert ("Login successfully");
console.log("Redirecting to welcome page...")
window.location = "success_new.html"; //redirecting to other page
return false;
}
else{
attempt --;//Decrementing by one
alert("You have left "+attempt+" attempt;");
}
//Disabling fields after 3 attempts
if( attempt == 0){
document.getElementById("username").disabled = true;
document.getElementById("password").disabled = true;
document.getElementById("submit").disabled = true;
return false;
}
}
</script>
</body>
</html>
At last I fix it. The issue here was "return" function on the onclick listener. here is that one
add return before the validate function
<button type="submit" id="login" onclick=" return validate()">Login</button>
Then it's works fine.
var username = document.getElementById('uname');
var pwd = document.getElementById('psw');
document.getElementById("b").onclick = function(){
if(username.value == "root" && pwd.value == "root"){
console.log("Redirecting to welcome page...")
window.location = "welcome.html";
}
}
<h2 text-align:"center">Authentication Required</h2>
<button onclick="document.getElementById('id01').style.display='block';">Login</button>
<div id="id01" class="modal" style="display:none;">
<form class="modal-content animate" action="">
<div class="imgcontainer">
<span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">×</span>
<img src="../images/logo1.png" alt="Logo" class="logo1">
</div>
<div class="container">
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="uname" id="uname" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" id="psw" required>
<button type="button" id="b">Login</button>
<input type="checkbox" checked="checked"> Remember me
</div>
<div class="container" style="background-color:#f1f1f1">
<button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>
<span class="psw">Forgot password?</span>
</div>
</form>
</div>
<script>
// Get the modal
var modal = document.getElementById('id01');
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
Fixed it. If I were you, I'd go over these and look at each difference to see what went wrong. It should be noted that you shouldn't do client-side validation like this, because anyone can easily:
See the password and username
Go to the url directly
Etc.
You really should do this server-side.