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

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:

Related

my html form on submitting is not calling the function password validation is there anything wrong with the code?

<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>

Cannot set property 'className' of null on form verification js script

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

Disable button untill all fields are cleared

I'm working on a simple contact form where I add custom validation aside from requiring all fields like email format, numbers for contact number and only letters for name. The validations are working but my problem is how to disable the button if all fields are not cleared.
what I've done right now is disabled the button on default and when one field is cleared the button is enabled even the others fields are empty.
The button must enable if the all fields are cleared from the validations.
Hope you help me.
Thanks.
// form validation
jQuery(function ($) {
$('form .form-control').keyup(function () {
let formBtn = true;
$(this).each(function () {
if ($(this).val().length === 0) {
$(this).closest('.form-group').find('span').addClass('text-warning').text('this is a required field');
formBtn = true;
} else {
formBtn = false;
$(this).closest('.form-group').find('span').removeClass().text('');
// CHECK IF EMAIL FORMAT IS VALID
if ($(this).attr('name') == 'email') {
if (!validateEmail($(this).val())) {
$(this).closest('.form-group').find('span').addClass('text-warning').text('invalid email format');
}
}
if ($(this).attr('name') == 'name') {
if (!validateName($(this).val())) {
$(this).closest('.form-group').find('span').addClass('text-warning').text('Only letters, spacing, hypen(-) and period are allowed.');
}
}
if ($(this).attr('name') == 'contactNumber') {
if (!validateContactNumber($(this).val())) {
$(this).closest('.form-group').find('span').addClass('text-warning').text('Only Numbers are allowed.');
} else if (validateContactNumber($(this).val()) == "invalidLength") {
$(this).closest('.form-group').find('span').addClass('text-warning').text('9-15 numbers are allowed.');
}
}
}
$(this).closest('form').find('button').prop('disabled',formBtn);
});
});
// VALIDATE NAME
function validateName(name) {
var regex = /^[a-zA-Z-.\s]*$/;
if (regex.test(name)) {
return true;
} else {
return false;
}
}
// VALIDATE EMAIL
function validateEmail(email) {
var regex = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
if (regex.test(email)) {
return true;
} else {
return false;
}
}
// VALIDATE PHONE NUMBER
function validateContactNumber(number) {
var numValid = /^[0-9]+$/;
var lenValid = /^.{9,15}$/;
if (numValid.test(number)) {
if (lenValid.test(number)) {
return true;
}else{
return 'invalidLength';
}
} else {
return false;
}
}
});
label{
display: inline-block;
margin-bottom: 6px;
letter-spacing: .025em;
color: #2A363B;
}
.form-group span{
text-transform: uppercase;
font-size: 11px;
}
.form-control{
padding: 12px 25px 12px 25px !important;
line-height: 24px !important;
border-radius: 0;
font-weight: 400;
height: auto;
border: 1px solid #e0e0e0;
box-shadow: none;
transition: .3s ease-in-out;
background-color: #fcfcfc;
color: #2A363B;
}
.form-control:focus {
border-color: rgba(30, 30, 40, .5);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 4px rgba(30, 30, 40, .3);
}
.btn{
padding: 14px 30px;
border-radius: 0;
}
.btn-default{
background-color: #2A363B;
border: 1px solid #2A363B;
color: #FFF;
transition: .3s ease-in-out;
}
.btn-default:focus,
.btn-default:hover{
background-color: #2A363B;
border: 1px solid #2A363B;
color: #FFF;
opacity: 0.7 !important;
}
.btn[disabled]{
background-color: #FFF;
border: 1px solid #ccc;
color: #222;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="container">
<div class="col-md-offset-3 col-md-6">
<form class="form-horizontal" autocomplete="off" method="post">
<div class="form-group">
<label for="subject" class="control-label">Subject</label>
<input type="text" class="form-control" id="subject" name="subject">
<span></span>
</div>
<div class="form-group">
<label for="name" class="control-label">Name</label>
<input type="text" class="form-control" id="name" name="name">
<span></span>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="email" class="control-label">Email</label>
<input type="email" class="form-control" id="email" name="email">
<span></span>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="contactNumber" class="control-label">Contact Number</label>
<input type="text" class="form-control" id="contactNumber" name="contactNumber">
<span></span>
</div>
</div>
</div>
<div class="form-group">
<label for="message" class="control-label">Message</label>
<textarea name="message" id="message" cols="30" rows="10" class="form-control" name="message"></textarea>
<span></span>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-4">
<button type="submit" class="btn btn-default btn-block" name="contactBtn" disabled >SUBMIT</button>
</div>
</div>
</form>
</div>
</div>
try this
jQuery(function($) {
$('form .form-control').keyup(function() {
let formBtn = true;
$(this).each(function() {
if ($(this).val().length === 0) {
$(this).closest('.form-group').find('span').addClass('text-warning').text('this is a required field');
formBtn = true;
} else {
// formBtn = false;
$(this).closest('.form-group').find('span').removeClass().text('');
// CHECK IF EMAIL FORMAT IS VALID
if ($(this).attr('name') == 'email') {
if (!validateEmail($(this).val())) {
$(this).closest('.form-group').find('span').addClass('text-warning').text('invalid email format');
}
}
if ($(this).attr('name') == 'name') {
if (!validateName($(this).val())) {
$(this).closest('.form-group').find('span').addClass('text-warning').text('Only letters, spacing, hypen(-) and period are allowed.');
}
}
if ($(this).attr('name') == 'contactNumber') {
if (!validateContactNumber($(this).val())) {
$(this).closest('.form-group').find('span').addClass('text-warning').text('Only Numbers are allowed.');
} else if (validateContactNumber($(this).val()) == "invalidLength") {
$(this).closest('.form-group').find('span').addClass('text-warning').text('9-15 numbers are allowed.');
}
}
var len = $('input[type=text],textarea').filter(function() {
return $(this).val().length == 0
}).length;
var warlen = $('.text-warning').filter(function() {
return $(this).text().length > 0
}).length;
if (len == 0 && warlen == 0) {
formBtn = false;
}
}
$(this).closest('form').find('button').prop('disabled', formBtn);
});
});
// VALIDATE NAME
function validateName(name) {
var regex = /^[a-zA-Z-.\s]*$/;
if (regex.test(name)) {
return true;
} else {
return false;
}
}
// VALIDATE EMAIL
function validateEmail(email) {
var regex = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
if (regex.test(email)) {
return true;
} else {
return false;
}
}
// VALIDATE PHONE NUMBER
function validateContactNumber(number) {
var numValid = /^[0-9]+$/;
var lenValid = /^.{9,15}$/;
if (numValid.test(number)) {
if (lenValid.test(number)) {
return true;
} else {
return 'invalidLength';
}
} else {
return false;
}
}
});
DEMO HERE
You can't true your button value on validating of single textbox or single text area you need to validate your whole form and then have to enable your button. Your logic for enabling and disabling button doesn't make any sense.
// form validation
jQuery(function ($) {
$('form .form-control').keyup(function () {
let formBtn = true;
$(this).each(function () {
if ($(this).val().length === 0) {
$(this).closest('.form-group').find('span').addClass('text-warning').text('this is a required field');
} else {
$(this).closest('.form-group').find('span').removeClass().text('');
// CHECK IF EMAIL FORMAT IS VALID
if ($(this).attr('name') == 'email') {
if (!validateEmail($(this).val())) {
$(this).closest('.form-group').find('span').addClass('text-warning').text('invalid email format');
formBtn = true;
}
else
formBtn = false;
}
if ($(this).attr('name') == 'name') {
if (!validateName($(this).val())) {
$(this).closest('.form-group').find('span').addClass('text-warning').text('Only letters, spacing, hypen(-) and period are allowed.');
formBtn = true;
}
else
formBtn = false;
}
if ($(this).attr('name') == 'contactNumber') {
if (!validateContactNumber($(this).val())) {
$(this).closest('.form-group').find('span').addClass('text-warning').text('Only Numbers are allowed.');
} else if (validateContactNumber($(this).val()) == "invalidLength") {
$(this).closest('.form-group').find('span').addClass('text-warning').text('9-15 numbers are allowed.');
formBtn = true;
}
else
formBtn = false;
}
}
$('input[type=text],textarea').each(function () {
if ($(this).val().length === 0) {
formBtn = true;
}
});
$(this).closest('form').find('button').prop('disabled',formBtn);
});
});
// VALIDATE NAME
function validateName(name) {
var regex = /^[a-zA-Z-.\s]*$/;
if (regex.test(name)) {
return true;
} else {
return false;
}
}
// VALIDATE EMAIL
function validateEmail(email) {
var regex = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
if (regex.test(email)) {
return true;
} else {
return false;
}
}
// VALIDATE PHONE NUMBER
function validateContactNumber(number) {
var numValid = /^[0-9]+$/;
var lenValid = /^.{9,15}$/;
if (numValid.test(number)) {
if (lenValid.test(number)) {
return true;
}else{
return 'invalidLength';
}
} else {
return false;
}
}
});
label{
display: inline-block;
margin-bottom: 6px;
letter-spacing: .025em;
color: #2A363B;
}
.form-group span{
text-transform: uppercase;
font-size: 11px;
}
.form-control{
padding: 12px 25px 12px 25px !important;
line-height: 24px !important;
border-radius: 0;
font-weight: 400;
height: auto;
border: 1px solid #e0e0e0;
box-shadow: none;
transition: .3s ease-in-out;
background-color: #fcfcfc;
color: #2A363B;
}
.form-control:focus {
border-color: rgba(30, 30, 40, .5);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 4px rgba(30, 30, 40, .3);
}
.btn{
padding: 14px 30px;
border-radius: 0;
}
.btn-default{
background-color: #2A363B;
border: 1px solid #2A363B;
color: #FFF;
transition: .3s ease-in-out;
}
.btn-default:focus,
.btn-default:hover{
background-color: #2A363B;
border: 1px solid #2A363B;
color: #FFF;
opacity: 0.7 !important;
}
.btn[disabled]{
background-color: #FFF;
border: 1px solid #ccc;
color: #222;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="container">
<div class="col-md-offset-3 col-md-6">
<form class="form-horizontal" autocomplete="off" method="post">
<div class="form-group">
<label for="subject" class="control-label">Subject</label>
<input type="text" class="form-control" id="subject" name="subject">
<span></span>
</div>
<div class="form-group">
<label for="name" class="control-label">Name</label>
<input type="text" class="form-control" id="name" name="name">
<span></span>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="email" class="control-label">Email</label>
<input type="email" class="form-control" id="email" name="email">
<span></span>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="contactNumber" class="control-label">Contact Number</label>
<input type="text" class="form-control" id="contactNumber" name="contactNumber">
<span></span>
</div>
</div>
</div>
<div class="form-group">
<label for="message" class="control-label">Message</label>
<textarea name="message" id="message" cols="30" rows="10" class="form-control" name="message"></textarea>
<span></span>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-4">
<button type="submit" class="btn btn-default btn-block" name="contactBtn" disabled >SUBMIT</button>
</div>
</div>
</form>
</div>
</div>
You can simply add required attribute. This is the best easiest workaround.
// form validation
jQuery(function ($) {
$('form .form-control').keyup(function () {
let formBtn = true;
$(this).each(function () {
if ($(this).val().length === 0) {
$(this).closest('.form-group').find('span').addClass('text-warning').text('this is a required field');
formBtn = true;
} else {
formBtn = false;
$(this).closest('.form-group').find('span').removeClass().text('');
// CHECK IF EMAIL FORMAT IS VALID
if ($(this).attr('name') == 'email') {
if (!validateEmail($(this).val())) {
$(this).closest('.form-group').find('span').addClass('text-warning').text('invalid email format');
}
}
if ($(this).attr('name') == 'name') {
if (!validateName($(this).val())) {
$(this).closest('.form-group').find('span').addClass('text-warning').text('Only letters, spacing, hypen(-) and period are allowed.');
}
}
if ($(this).attr('name') == 'contactNumber') {
if (!validateContactNumber($(this).val())) {
$(this).closest('.form-group').find('span').addClass('text-warning').text('Only Numbers are allowed.');
} else if (validateContactNumber($(this).val()) == "invalidLength") {
$(this).closest('.form-group').find('span').addClass('text-warning').text('9-15 numbers are allowed.');
}
}
}
$(this).closest('form').find('button').prop('disabled',formBtn);
});
});
// VALIDATE NAME
function validateName(name) {
var regex = /^[a-zA-Z-.\s]*$/;
if (regex.test(name)) {
return true;
} else {
return false;
}
}
// VALIDATE EMAIL
function validateEmail(email) {
var regex = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
if (regex.test(email)) {
return true;
} else {
return false;
}
}
// VALIDATE PHONE NUMBER
function validateContactNumber(number) {
var numValid = /^[0-9]+$/;
var lenValid = /^.{9,15}$/;
if (numValid.test(number)) {
if (lenValid.test(number)) {
return true;
}else{
return 'invalidLength';
}
} else {
return false;
}
}
});
label{
display: inline-block;
margin-bottom: 6px;
letter-spacing: .025em;
color: #2A363B;
}
.form-group span{
text-transform: uppercase;
font-size: 11px;
}
.form-control{
padding: 12px 25px 12px 25px !important;
line-height: 24px !important;
border-radius: 0;
font-weight: 400;
height: auto;
border: 1px solid #e0e0e0;
box-shadow: none;
transition: .3s ease-in-out;
background-color: #fcfcfc;
color: #2A363B;
}
.form-control:focus {
border-color: rgba(30, 30, 40, .5);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 4px rgba(30, 30, 40, .3);
}
.btn{
padding: 14px 30px;
border-radius: 0;
}
.btn-default{
background-color: #2A363B;
border: 1px solid #2A363B;
color: #FFF;
transition: .3s ease-in-out;
}
.btn-default:focus,
.btn-default:hover{
background-color: #2A363B;
border: 1px solid #2A363B;
color: #FFF;
opacity: 0.7 !important;
}
.btn[disabled]{
background-color: #FFF;
border: 1px solid #ccc;
color: #222;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="container">
<div class="col-md-offset-3 col-md-6">
<form class="form-horizontal" autocomplete="off" method="post">
<div class="form-group">
<label for="subject" class="control-label">Subject</label>
<input type="text" class="form-control" id="subject" name="subject" required>
<span></span>
</div>
<div class="form-group">
<label for="name" class="control-label">Name</label>
<input type="text" class="form-control" id="name" name="name" required>
<span></span>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="email" class="control-label">Email</label>
<input type="email" class="form-control" id="email" name="email" required>
<span></span>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="contactNumber" class="control-label">Contact Number</label>
<input type="text" class="form-control" id="contactNumber" name="contactNumber" required>
<span></span>
</div>
</div>
</div>
<div class="form-group">
<label for="message" class="control-label">Message</label>
<textarea name="message" id="message" cols="30" rows="10" class="form-control" name="message" required></textarea>
<span></span>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-4">
<button type="submit" class="btn btn-default btn-block" name="contactBtn" disabled >SUBMIT</button>
</div>
</div>
</form>
</div>
</div>

Contact Form validation error using jquery

I'm doing contact form by passing value dynamically for all inputs fields.i have two forms on the same page using id i passed values. In js same code for these two forms. The problem is after passing correct value also it is showing an error and if I submit form1 then form2 also getting submitted. Here validations are not working I tried everything is correct what might be the problem.
$(document).ready(function() {
/* contact form tabs*/
function button() {
$('.demos-nav .iva-nav').click(function() {
var btn = $(this).data('btn');
$('.row').removeClass('current').css('display', 'none');
$('.demos-nav .iva-nav').removeClass('current');
$(this).addClass('current');
$("#" + btn).addClass('current').css('display', 'block');
})
}
button();
/* name*/
$("[class^='form_']").on('input', function() {
var input = $(this);
var is_name = input.val();
if (is_name) {
input.removeClass("invalid").addClass("valid");
} else {
input.removeClass("valid").addClass("invalid");
}
});
/* E-mail */
$("[class^='form_']").on('input', function() {
var input = $(this);
var regex = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
var is_email = regex.test(input.val());
if (is_email) {
input.removeClass("invalid").addClass("valid");
} else {
input.removeClass("valid").addClass("invalid");
}
});
/* Phone */
$("[class^='form_']").on('input', function() {
var input = $(this);
var regex = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
var is_phone = regex.test(input.val());
if (is_phone) {
input.removeClass("invalid").addClass("valid");
} else {
input.removeClass("valid").addClass("invalid");
}
});
/* select People*/
$("[class^='form_']").change(function() {
var select = $(this);
var selectOption = $("#contact_select option:selected").val();
if (selectOption) {
select.removeClass("invalid").addClass("valid");
} else {
select.removeClass("valid").addClass("invalid");
}
});
/* select Time*/
$("[class^='form_']").change(function() {
var select = $(this);
var selectTime = $("#contact_time option:selected").val();
if (selectTime) {
select.removeClass("invalid").addClass("valid");
} else {
select.removeClass("valid").addClass("invalid");
}
});
/* Enquiry message*/
$("[class^='form_']").keyup(function(event) {
var input = $(this);
var enquiry = $(this).val();
if (enquiry) {
input.removeClass("invalid").addClass("valid");
} else {
input.removeClass("valid").addClass("invalid");
}
});
/* message*/
$("[class^='form_']").keyup(function(event) {
var input = $(this);
var message = $(this).val();
if (message) {
input.removeClass("invalid").addClass("valid");
} else {
input.removeClass("valid").addClass("invalid");
}
});
/* Submit */
$("[id^='submit_']").click(function(event) {
var form_data = $("[id^='form_']").serializeArray();
var error_free = true;
for (var input in form_data) {
var element = $("#contact_" + form_data[input]['name']);
var valid = element.hasClass("valid");
var error_element = $("span", element.parent());
if (!valid) {
error_element.removeClass("error").addClass("error_show");
error_free = false;
} else {
error_element.removeClass("error_show").addClass("error");
}
}
if (!error_free) {
return false;
} else {
$('.success_msg').fadeIn().delay(3000).fadeOut();
$('input , textarea , select').val('').removeClass('valid');
event.preventDefault();
}
});
});
.wrapper {
max-width: 1440px;
width: 100%;
margin: 0 auto;
position: relative;
}
.demos-nav {
position: relative;
display: flex;
flex-wrap: wrap;
margin: 40px auto;
justify-content: center;
align-items: center;
max-width: 1140px;
}
.success_msg {
width: 350px;
line-height: 40px;
border: 1px solid green;
border-radius: 5px;
background-color: rgba(213, 255, 187, 0.7);
display: none;
position: absolute;
bottom: 50px;
left: 50%;
transform: translateX(-50%);
z-index: 999;
text-align: center;
}
.iva-nav {
width: 100px;
text-align: center;
color: #fff;
font-size: 16px;
font-weight: 600;
transition: all 0.74s ease;
margin: 10px;
padding: 10px;
cursor: pointer;
position: relative;
transition: all .7s ease-in-out;
}
.iva-nav span {
transform: translateZ(8px);
user-select: none;
position: relative;
z-index: 999;
}
.iva-nav:before {
content: '';
position: absolute;
padding: 10px;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(254, 180, 29, 0.3);
box-sizing: border-box;
border: 1px solid rgba(255, 225, 225, 0.4);
transition: all 0.5s ease-in-out;
z-index: 50;
}
.iva-nav:after {
content: '';
position: absolute;
padding: 10px;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(254, 180, 29, 0.3);
box-sizing: border-box;
border: 1px solid rgba(255, 225, 225, 0.4);
transition: all 0.6s ease-in-out;
z-index: 25;
}
/*.iva-nav:hover {
transform: rotateX(-180deg) rotateY(180deg) rotateZ(180deg) ;
}*/
.iva-nav:hover:before {
transform: rotate(225deg);
background-color: rgba(254, 180, 29, 0.6);
border: 1px solid rgba(255, 225, 225, 0.1);
}
.iva-nav:hover:after {
transform: rotate(133deg);
background-color: rgba(254, 180, 29, 0.6);
border: 1px solid rgba(255, 225, 225, 0.1);
}
.fancy-heading-s1 {
max-width: 1400px;
width: 100%;
margin: 0 auto;
font-size: 40px;
padding: 25px 0;
color: #ffffff;
}
.fancy-heading-s2 {
font-size: 30px;
margin: 20px 0;
color: #fff;
}
.fancy-title {
display: block;
font-size: 13px;
margin: 20px 0;
font-weight: 400;
color: #ffffff;
}
.cfar-s1 .cfar-heading {
text-align: center;
}
*:focus {
outline: none;
}
.cfar {
max-width: 1140px;
width: 100%;
margin: 0 auto;
position: relative;
box-sizing: border-box;
}
.cfar-s1 {
padding: 40px 100px;
background-color: #313439;
}
.cfar-s1 .fancy-title span {
position: relative;
text-transform: uppercase;
cursor: pointer;
}
.cfar-s1 .fancy-title span:after {
content: " . ";
position: relative;
top: 50%;
display: inline-block;
transform: translateY(-15%);
margin: 0 10px;
}
.cfar-s1 .fancy-title span:last-child:after {
content: "";
margin-right: 0;
}
.cfar-s1 .fancy-heading-s2 h2 {
font-size: 40px;
font-weight: bold;
text-transform: uppercase;
}
.cfar-s1 .fancy-heading-s2 h2 span {
color: #da4e5b;
}
.cfar-s1 form {
padding: 30px 0;
display: flex;
flex-wrap: wrap;
justify-content: space-between;
}
.cfar .detail {
position: relative;
margin: 20px 0;
flex-basis: 48%;
}
.cfar .detail input,
.detail textarea,
.detail select {
display: block;
border: none;
border-bottom: 1px solid #fff;
padding: 5px 0;
width: 100%;
background: none;
color: #ffffff;
}
.cfar option {
background: rgba(0, 0, 0, 0.8);
}
.cfar .detail textarea {
height: 100px;
width: 100%;
overflow: auto;
resize: none;
}
.cfar .detail label {
position: absolute;
top: 0px;
left: 5px;
font-size: 16px;
pointer-events: none;
transition: all 0.43s ease-in-out;
}
.cfar .detail .inputBar {
position: relative;
display: block;
transition: all 0.43s ease-in-out;
}
.cfar .detail input:focus:after,
.detail textarea:foucs:after,
.detail select:focus:after,
.cfar .detail .inputBar:focus:before,
.cfar .detail .inputBar:focus:after {
content: "";
display: block;
position: absolute;
bottom: 0;
width: 0;
background: red;
height: 2px;
}
.cfar .detail .inputBar:after {
right: 50%;
}
.cfar .detail .inputBar:before {
left: 50%;
}
.cfar .detail input:focus~label,
.cfar .detail input:valid~label,
.cfar .detail textarea:focus~label,
.cfar .detail textarea:valid~label {
top: -20px;
transition: all 0.3s ease-in-out;
font-size: 13px;
}
.cfar .detail input:focus~.inputBar:before,
.cfar .detail input:focus~.inputBar:after,
.cfar .detail textarea:focus~.inputBar:before,
.cfar .detail textarea:focus~.inputBar:after .cfar .detail select:focus~.inputBar:before,
.cfar .detail select:focus~.inputBar:after {
width: 50%;
}
.cfar .detail .answer {
display: inline-block;
width: 114px;
height: 20px;
border: 1px solid #ffffff;
left: 133px;
position: inherit;
}
/* custom css*/
span.error {
/*display: none;*/
color: red;
opacity: 0;
position: absolute;
top: 10px !important;
right: 0;
transition: all 0.4s ease-in-out;
}
.error_show {
position: absolute;
top: 0;
right: 0;
color: red;
}
/*input.invalid,
textarea.invalid,
select.invalid {
border: 2px solid red;
}*/
input:focus {
outline-width: 0;
}
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
margin: 0;
background-color: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="demos-nav">
<div class="iva-nav demo1" data-btn="demo1"><span>Demo 1</span></div>
<div class="iva-nav demo2" data-btn="demo2"><span>Demo 2</span></div>
</div>
<!-- demos nav -->
<div class="row current" id="demo1">
<div class="cfar cfar-s1">
<form id="form_info1" method="post" action="">
<div class="detail">
<input type="text" class="form_name1" id="contact_name1" name="name1" required autocomplete="off" />
<span class="inputBar"></span>
<!--inputBar-->
<label for="contact_name1">Name</label>
<span class="error">This field is required</span>
</div>
<!--detail-->
<div class="detail">
<input type="text" class="form_email1" id="contact_email1" name="email1" required autocomplete="off" />
<span class="inputBar"></span>
<!--inputBar-->
<label for="contact_email1">Email</label>
<span class="error">A valid email address is required</span>
</div>
<!--detail-->
<div class="detail">
<input type="number" class="form_phone1" id="contact_phone1" name="phone1" required autocomplete="off" />
<span class="inputBar"></span>
<!--inputBar-->
<label for="contact_phone1">Phone Number</label>
<span class="error">A valid Phone number is required</span>
</div>
<!--detail-->
<div class="detail">
<input type="text" class="form_enquiry1" id="contact_enquiry1" name="enquiry1" required autocomplete="off" />
<span class="inputBar"></span>
<!--inputBar-->
<label for="contact_enquiry">I want to know about...</label>
<span class="error">This field is required</span>
</div>
<!--detail-->
<div class="detail message">
<textarea type="text" class="form_message1" id="contact_message1" name="message1" required></textarea>
<span class="inputBar"></span>
<!--inputBar-->
<label for="contact_message1">Type your Message here</label>
<span class="error">This field is required</span>
</div>
<!--detail-->
<div class="btn-container" id="submit_form1">
<button type="submit" class="btn"> Submit</button>
</div>
</form>
<div class="success_msg">
<p>Form submitted Successfully</p>
</div>
</div>
<!-- Contact Form style 1 -->
</div>
<!-- row demo 1-->
<div class="row" id="demo2">
<div class="cfar cfar-s2">
<div class="cfar-form">
<h2 class="fancy-heading-s2"> Contact us </h2>
<span class="fancy-title"> Reach out to us for any Inquiry</span>
<form id="form_info2" method="post" action="">
<div class="detail">
<input type="text" class="form_name2" id="contact_name2" name="name2" required autocomplete="off" />
<span class="inputBar"></span>
<!--inputBar-->
<label for="contact_name2">Name</label>
<span class="error">This field is required</span>
</div>
<!--detail-->
<div class="detail">
<input type="text" class="form_email2" id="contact_email2" name="email2" required autocomplete="off" />
<span class="inputBar"></s1pan><!--inputBar-->
<label for="contact_email2">Email</label>
<span class="error">A valid email address is required</span>
</div>
<!--detail-->
<div class="detail">
<input type="number" class="form_phone2" id="contact_phone2" name="phone2" required autocomplete="off" />
<span class="inputBar"></span>
<!--inputBar-->
<label for="contact_phone2">Phone Number</label>
<span class="error">A valid Phone number is required</span>
</div>
<!--detail-->
<div class="detail message">
<textarea type="text" class="form_message2" id="contact_message2" name="message2" required></textarea>
<span class="inputBar"></span>
<!--inputBar-->
<label for="contact_message2">Type your Message here</label>
<span class="error">This field is required</span>
</div>
<!--detail-->
<div class="btn-container" id="submit_form2">
<button type="submit" class="btn"> Submit</button>
</div>
</form>
</div>
</div>
<!-- Contact Form style 2 -->
</div>
<!-- row demo 2-->
</div>
Do the following changes in your code and design.
In html, change button tag to input tag,
<div class="wrapper">
<div class="demos-nav">
<div class="iva-nav demo1" data-btn="demo1"><span>Demo 1</span></div>
<div class="iva-nav demo2" data-btn="demo2"><span>Demo 2</span></div>
</div>
<!-- demos nav -->
<div class="row current" id="demo1">
<div class="cfar cfar-s1">
<form id="form_info1" method="post" action="">
<div class="detail">
<input type="text" class="form_name1" id="contact_name1" name="name1" required autocomplete="off" />
<span class="inputBar"></span>
<!--inputBar-->
<label for="contact_name1">Name</label>
<span class="error">This field is required</span>
</div>
<!--detail-->
<div class="detail">
<input type="text" class="form_email1" id="contact_email1" name="email1" required autocomplete="off" />
<span class="inputBar"></span>
<!--inputBar-->
<label for="contact_email1">Email</label>
<span class="error">A valid email address is required</span>
</div>
<!--detail-->
<div class="detail">
<input type="text" class="form_phone1" id="contact_phone1" name="phone1" required autocomplete="off" />
<span class="inputBar"></span>
<!--inputBar-->
<label for="contact_phone1">Phone Number</label>
<span class="error">A valid Phone number is required</span>
</div>
<!--detail-->
<div class="detail">
<input type="text" class="form_enquiry1" id="contact_enquiry1" name="enquiry1" required autocomplete="off" />
<span class="inputBar"></span>
<!--inputBar-->
<label for="contact_enquiry">I want to know about...</label>
<span class="error">This field is required</span>
</div>
<!--detail-->
<div class="detail message">
<textarea type="text" class="form_message1" id="contact_message1" name="message1" required></textarea>
<span class="inputBar"></span>
<!--inputBar-->
<label for="contact_message1">Type your Message here</label>
<span class="error">This field is required</span>
</div>
<!--detail-->
<div class="btn-container" id="submit_form1">
<input type="button" class="btn" value="Submit"/>
</div>
</form>
<div class="success_msg">
<p>Form submitted Successfully</p>
</div>
</div>
<!-- Contact Form style 1 -->
</div>
<!-- row demo 1-->
<div class="row" id="demo2">
<div class="cfar cfar-s2">
<div class="cfar-form">
<h2 class="fancy-heading-s2"> Contact us </h2>
<span class="fancy-title"> Reach out to us for any Inquiry</span>
<form id="form_info2" method="post" action="">
<div class="detail">
<input type="text" class="form_name2" id="contact_name2" name="name2" required autocomplete="off" />
<span class="inputBar"></span>
<!--inputBar-->
<label for="contact_name2">Name</label>
<span class="error">This field is required</span>
</div>
<!--detail-->
<div class="detail">
<input type="text" class="form_email2" id="contact_email2" name="email2" required autocomplete="off" />
<span class="inputBar">
</s1pan><!--inputBar-->
<label for="contact_email2">Email</label>
<span class="error">A valid email address is required</span>
</div>
<!--detail-->
<div class="detail">
<input type="text" class="form_phone2" id="contact_phone2" name="phone2" required autocomplete="off" />
<span class="inputBar"></span>
<!--inputBar-->
<label for="contact_phone2">Phone Number</label>
<span class="error">A valid Phone number is required</span>
</div>
<!--detail-->
<div class="detail message">
<textarea type="text" class="form_message2" id="contact_message2" name="message2" required></textarea>
<span class="inputBar"></span>
<!--inputBar-->
<label for="contact_message2">Type your Message here</label>
<span class="error">This field is required</span>
</div>
<!--detail-->
<div class="btn-container" id="submit_form2">
<input type="button" class="btn" value="Submit"/>
</div>
</form>
</div>
</div>
<!-- Contact Form style 2 -->
</div>
<!-- row demo 2-->
</div>
The script is,
$(document).ready(function () {
/* contact form tabs*/
function button() {
$('.demos-nav .iva-nav').click(function () {
var btn = $(this).data('btn');
$('.row').removeClass('current').css('display', 'none');
$('.demos-nav .iva-nav').removeClass('current');
$(this).addClass('current');
$("#" + btn).addClass('current').css('display', 'block');
})
}
button();
/* name*/
$("[class^='form_name']").on('change', function () {
var input = $(this);
var is_name = input.val();
if (is_name) {
$(input).removeClass("invalid");
$(input).addClass("valid");
} else {
$(input).removeClass("valid");
$(input).addClass("invalid");
}
});
/* E-mail */
$("[class^='form_email']").on('change', function () {
var input = $(this);
var regex = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
var is_email = regex.test(input.val());
if (is_email) {
input.removeClass("invalid").addClass("valid");
} else {
input.removeClass("valid").addClass("invalid");
}
});
/* Phone */
$("[class^='form_phone']").on('change', function () {
var input = $(this);
var regex = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
var is_phone = regex.test(input.val());
if (is_phone) {
input.removeClass("invalid").addClass("valid");
} else {
input.removeClass("valid").addClass("invalid");
}
});
/* Enquiry message*/
$("[class^='form_enquiry']").keyup(function (event) {
var input = $(this);
var enquiry = $(this).val();
if (enquiry) {
input.removeClass("invalid").addClass("valid");
} else {
input.removeClass("valid").addClass("invalid");
}
});
/* message*/
$("[class^='form_message']").keyup(function (event) {
var input = $(this);
var message = $(this).val();
if (message) {
input.removeClass("invalid").addClass("valid");
} else {
input.removeClass("valid").addClass("invalid");
}
});
/* Submit */
$("[id^='submit_']").click(function (event) {
var form_data = $(this).parent().serializeArray();
var error_free = true;
for (var input in form_data) {
var element = $("#contact_" + form_data[input]['name']);
var valid = element.hasClass("valid");
var error_element = $("span", element.parent());
if (!valid) {
error_element.removeClass("error").addClass("error_show");
error_free = false;
} else {
error_element.removeClass("error_show").addClass("error");
}
}
if (!error_free) {
return false;
} else {
$('.success_msg').fadeIn().delay(3000).fadeOut();
$('input , textarea , select').val('').removeClass('valid');
event.preventDefault();
}
});
});
In the submit handler, you are referencing both the forms. which is why validations in both the forms are firing. Try getting the reference of the form to which the clicked submit button belongs to.
$("[id^='submit_']").click(function(event) {
var form = $(this).closest("form");
var form_data = form.serializeArray();
//remaining code
Hope this gives you an idea.
Did you try to use newest version of jQuery?? Like: 3.3.1
updated
Try to change all your if statements for example:
/* name*/
$("[class^='form_']").on('input', function() {
var input = $(this);
var is_name = input.val();
if (is_name === ' ') {
input.removeClass("valid").addClass("invalid");
} else {
input.removeClass("invalid").addClass("valid");
}
});
codepen

How to validate a multiple step form and message display for each and every fields

How to validate a multiple step form and message display for each and every fields example:please enter your email and I also want all the error message to
be display at the same time :suppose I click on next button I should display all How to validate a multiple step form and message display for each and every feilds How to validate a multiple step form and message display for each and every fields
function isEmail(str) { // simple email validation
return /(.+)#(.+){2,}\.(.+){2,}/.test($.trim(str));
}
function isEmpty(str) { // test for empty string
return $.trim(str) === "";
}
function validate($div) { // validates any div - will not let you leave the div if error
var $fields = $div.find("input"), hasError = false;
$fields.each(function() {
$(this).removeClass("error")
hasError = this.name=="pword" && isEmpty(this.value);
if (hasError) {
$("#pword").addClass("error").focus();
return false;
}
hasError = this.name=="email" && (isEmpty(this.value) || !isEmail(this.value));
if (hasError) {
$("#email").addClass("error").focus();
return false;
}
hasError = isEmpty(this.value); // the rest of the fields
if (hasError) {
$(this).addClass("error").focus();
return false;
}
})
return hasError?false:true;
}
$(function() {
// validate all divs on submit, but actually only necessary to validate thediv the submit is on
$("#myForm").on("submit",function(e) {
$(".page").each(function() {
if (!validate($(this))) {
e.preventDefault(); // stop submission
return false;
}
});
});
$(".nav").on("click", function() {
var $parent = $(this).closest("div");
var $nextDiv = $(this).hasClass("next") ? $parent.next() : $parent.prev();
if (validate($parent)) { // is the div this button is on valid?
$parent.fadeOut(function() { // fade it out and fade the next one in
if ($nextDiv.length) {
$nextDiv.fadeIn()
for (var i=$(".page").length;i> $nextDiv.index(); i--) {
$("#bar" + i).css({"background-color": "#D8D8D8"}); // we are going backwards
}
$("#bar" + $nextDiv.index()).css({"background-color": "#38610B"});
}
});
}
});
});
body {
margin: 0 auto;
padding: 0;
text-align: center;
background-color: #D8D8D8;
}
#wrapper {
width: 995px;
padding: 0px;
margin: 0px auto;
font-family: helvetica;
position: relative;
}
#wrapper .baricon {
display: inline-block;
border-radius: 100%;
padding: 12px;
background-color: #38610B;
color: white;
}
#wrapper .progress_bar {
width: 200px;
height: 5px;
border-radius: 20px;
background-color: #D8D8D8;
display: inline-block;
}
#wrapper form div {
margin-left: 340px;
padding: 10px;
box-sizing: border-box;
width: 300px;
margin-top: 50px;
background-color: #585858;
}
#wrapper form div p {
color: #F2F2F2;
margin: 0px;
margin-top: 10px;
font-weight: bold;
}
#wrapper form div .form_head {
font-size: 22px;
font-weight: bold;
margin-bottom: 30px;
}
#wrapper form div input[type="text"] {
width: 200px;
height: 40px;
padding: 5px;
border-radius: 5px;
border: none;
margin-top: 10px;
}
#wrapper form div input[type="button"],
input[type="submit"] {
width: 80px;
height: 40px;
border-radius: 5px;
border: 2px solid white;
background: none;
color: white;
margin: 5px;
margin-top: 10px;
}
#user_details,
#qualification {
display: none;
}
.error { background-color:pink !important}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="wrapper">
<br>
<span class='baricon'>1</span>
<span id="bar1" class='progress_bar'> </span>
<span class='baricon'>2</span>
<span id="bar2" class='progress_bar'> </span>
<span class='baricon'>3</span>
<form method="post" action="" id="myForm">
<div id="account_details" class="page">
<p class='form_head'>Account Details</p>
<p>Email Address</p>
<input type="text" name="email" id="email" placeholder='Email Address'>
<p>Password</p>
<input type="text" name="pword" id="pword" placeholder='Password'>
<br>
<input type="button" value="Next" class="nav next" />
</div>
<div id="user_details" class="page">
<p class='form_head'>User Details</p>
<p>First Name</p>
<input type="text" name="fname" id="fname" placeholder='First Name'>
<p>Last Name</p>
<input type="text" name="lname" is="lname" placeholder='Last Name'>
<p>Gender</p>
<input type="text" name="gender" id="gender" placeholder='Gender'>
<br>
<input type="button" value="Prev" class="nav prev" />
<input type="button" value="Next" class="nav next" />
</div>
<div id="qualification" class="page">
<p class='form_head'>Qualification</p>
<p>Qualification</p>
<input type="text" placeholder='Qualification'>
<p>Hobbies</p>
<input type="text" placeholder='Hobbies'>
<br>
<input type="button" value="Prev" class="nav prev" />
<input type="Submit" value="Submit">
</div>
</form>
</div>
You can use Jquery.validate.min.js file which contains validate method.
Refer the following code below:
function valid(){
$("#rform").validate({
rules:{
uname:"required", // uname, email are input names
umail:{
required:true,
email:true
},
upass:{
required:true,
minlength:8
}
},
messages:{
uname:"Please enter full name",
umail:{
required:"Please enter email id",
email:"Please enter valid email id"
},
upass:
{
required:"please provide password",
minlength:"min length of password is 8"
}
},
submitHandler :function(form){
// alert("it works!");
console.log("it works!");
// form.submit();
funreg(); //function to be called after submit button is pressed and al inputl fields are valids
}
});
}

Categories