JQuery Register Form Validation - javascript

I have this Registration Form for a website that contains basically :
Name
Lastname
Date of Birth
Email
Username
Password
Confirm Password
I was able to make a script which validates whether Each case of the Form is filled and for Email if it is a Valid email address or not. Now I'm stuck at how to make the Validation of whether the Full Name (will be made like this: Name+LastName), the Email and the Username exists in the Database or not. I tried with the jquery.validate plugin but i couldn't get to work..
Demo: https://jsfiddle.net/2y1bry24/4/
/*** Sign Up ***/
$(document).ready(function () {
$flag = 1;
/***** Personal Data Validation ****/
$("#name").focusout(function () {
if ($(this).val() == '') {
$(this).css("border-color", "#cd2d00");
$('#submit').attr('disabled', true);
$("#error_name").text("* You have to enter your first name!");
} else {
$(this).css("border-color", "#2eb82e");
$('#submit').attr('disabled', false);
$("#error_name").text("");
}
});
$("#lastname").focusout(function () {
if ($(this).val() == '') {
$(this).css("border-color", "#cd2d00");
$('#submit').attr('disabled', true);
$("#error_lastname").text("* You have to enter your last name!");
} else {
$(this).css("border-color", "#2eb82e");
$('#submit').attr('disabled', false);
$("#error_lastname").text("");
}
});
$("#dob").focusout(function () {
if ($(this).val() == '') {
$(this).css("border-color", "#cd2d00");
$('#submit').attr('disabled', true);
$("#error_dob").text("* You have to enter your Date of Birth!");
} else {
$(this).css("border-color", "#2eb82e");
$('#submit').attr('disabled', false);
$("#error_dob").text("");
}
});
/***** Email Validation ****/
function validateEmail(sEmail) {
var filter = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/;
if (filter.test(sEmail)) {
return true;
} else {
return false;
}
}
$("#email").focusout(function () {
var sEmail = $('#email').val();
if ($.trim(sEmail).length == 0) {
$(this).css("border-color", "#cd2d00");
$('#submit').attr('disabled', true);
$("#error_email").text("Please enter valid email address");
e.preventDefault();
}
if (validateEmail(sEmail)) {
$(this).css("border-color", "#2eb82e");
$('#submit').attr('disabled', false);
$("#error_email").text("");;
} else {
$(this).css("border-color", "#cd2d00");
$('#submit').attr('disabled', true);
$("#error_email").text("Invalid email address");
e.preventDefault();
}
});
/***** Login Data Validation ****/
$("#username").focusout(function () {
if ($(this).val() == '') {
$(this).css("border-color", "#cd2d00");
$('#submit').attr('disabled', true);
$("#error_username").text("* You have to enter your Username!");
} else {
$(this).css("border-color", "#2eb82e");
$('#submit').attr('disabled', false);
$("#error_username").text("");
}
});
$("#password").focusout(function () {
if ($(this).val() == '') {
$(this).css("border-color", "#cd2d00");
$('#submit').attr('disabled', true);
$("#error_password").text("* You have to enter your Password!");
} else {
$(this).css("border-color", "#2eb82e");
$('#submit').attr('disabled', false);
$("#error_password").text("");
}
});
$("#confirm").focusout(function () {
if ($("#confirm").val() !== $("#password").val()) {
$("#confirm").css("border-color", "#cd2d00");
$('#submit').attr('disabled', true);
$("#error_confirm").text("Passwords Do not match!");
} else {
$(this).css("border-color", "#2eb82e");
$('#submit').attr('disabled', false);
$("#error_confirm").text("");
}
});
/***+* Submit Validation ****/
$("#submit").click(function () {
if ($("#name").val() == '') {
$("#name").css("border-color", "#cd2d00");
$('#submit').attr('disabled', true);
$("#error_name").text("* You have to enter your first name!");
}
if ($("#lastname").val() == '') {
$("#lastname").css("border-color", "#cd2d00");
$('#submit').attr('disabled', true);
$("#error_lastname").text("* You have to enter your Last name!");
}
if ($("#dob").val() == '') {
$("#dob").css("border-color", "#cd2d00");
$('#submit').attr('disabled', true);
$("#error_dob").text("* You have to enter your Date of Birth!");
}
if ($("#email").val() == '') {
$("#email").css("border-color", "#FF0000");
$('#submit').attr('disabled', true);
$("#error_email").text("* You have to enter your Email !");
}
if ($("#username").val() == '') {
$("#username").css("border-color", "#cd2d00");
$('#submit').attr('disabled', true);
$("#error_username").text("* You have to enter your Username!");
}
if ($("#password").val() == '') {
$("#password").css("border-color", "#cd2d00");
$('#submit').attr('disabled', true);
$("#error_password").text("Enter a Password");
}
if ($("#confirm").val() == '') {
$("#confirm").css("border-color", "#cd2d00");
$('#submit').attr('disabled', true);
$("#error_confirm").text("Confirm Password");
}
});
});
/*** Sign-up ***/
#playground-container {
height: 500px;
overflow: hidden !important;
-webkit-overflow-scrolling: touch;
}
body,
html {
background-repeat: repeat-y;
background: url(https://i.ytimg.com/vi/4kfXjatgeEU/maxresdefault.jpg);
font-family: 'Oxygen', sans-serif;
background-size: cover;
}
.main {
margin: 50px 15px;
}
h1.title {
font-size: 50px;
font-family: 'Passion One', cursive;
font-weight: 400;
}
hr {
width: 10%;
color: #fff;
}
.form-group {
margin-bottom: 15px;
}
label {
margin-bottom: 15px;
}
input,
input::-webkit-input-placeholder {
font-size: 11px;
padding-top: 3px;
}
.main-login {
background-color: #fff;
/* shadows and rounded borders */
-moz-border-radius: 2px;
-webkit-border-radius: 2px;
border-radius: 2px;
-moz-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
-webkit-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
}
.form-control {
height: auto!important;
padding: 8px 12px !important;
}
.input-group {
-webkit-box-shadow: 0px 2px 5px 0px rgba(0, 0, 0, 0.21)!important;
-moz-box-shadow: 0px 2px 5px 0px rgba(0, 0, 0, 0.21)!important;
box-shadow: 0px 2px 5px 0px rgba(0, 0, 0, 0.21)!important;
}
#button {
border: 1px solid #ccc;
margin-top: 28px;
padding: 6px 12px;
color: #666;
text-shadow: 0 1px #fff;
cursor: pointer;
-moz-border-radius: 3px 3px;
-webkit-border-radius: 3px 3px;
border-radius: 3px 3px;
-moz-box-shadow: 0 1px #fff inset, 0 1px #ddd;
-webkit-box-shadow: 0 1px #fff inset, 0 1px #ddd;
box-shadow: 0 1px #fff inset, 0 1px #ddd;
background: #f5f5f5;
background: -moz-linear-gradient(top, #f5f5f5 0%, #eeeeee 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #f5f5f5), color-stop(100%, #eeeeee));
background: -webkit-linear-gradient(top, #f5f5f5 0%, #eeeeee 100%);
background: -o-linear-gradient(top, #f5f5f5 0%, #eeeeee 100%);
background: -ms-linear-gradient(top, #f5f5f5 0%, #eeeeee 100%);
background: linear-gradient(top, #f5f5f5 0%, #eeeeee 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#f5f5f5', endColorstr='#eeeeee', GradientType=0);
}
.main-center {
margin-top: 30px;
margin: 0 auto;
max-width: 400px;
padding: 10px 40px;
background: #588ba7;
color: #FFF;
text-shadow: none;
-webkit-box-shadow: 0px 3px 5px 0px rgba(0, 0, 0, 0.31);
-moz-box-shadow: 0px 3px 5px 0px rgba(0, 0, 0, 0.31);
box-shadow: 0px 3px 5px 0px rgba(0, 0, 0, 0.31);
}
span.input-group-addon i {
color: #009edf;
font-size: 17px;
}
.login-button {
margin-top: 5px;
}
.login-register {
font-size: 11px;
text-align: center;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
<div class="container">
<div class="row main">
<div class="main-login main-center">
<h5>Registrieren</h5>
<form id="register_form" name="register_form" method="post" action="index.php">
<div class="form-group">
<label for="name" class="cols-sm-2 control-label">Vorname</label>
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-user fa" aria-hidden="true"></i></span>
<input type="text" class="form-control" name="name" id="name" placeholder="Dein Vorname" data-validation="required" />
</div>
</div>
<span id="error_name" class="text-danger"></span>
</div>
<div class="form-group">
<label for="lastname" class="cols-sm-2 control-label">Nachname</label>
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-user fa" aria-hidden="true"></i></span>
<input type="text" class="form-control" name="lastname" id="lastname" placeholder="Dein Nachname" data-validation="required" />
</div>
</div>
<span id="error_lastname" class="text-danger"></span>
</div>
<div class="form-group">
<label for="dob" class="cols-sm-2 control-label">Geburtstag</label>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-calendar fa" aria-hidden="true"></i></span>
<input type="date" class="form-control" name="dob" id="dob" data-validation="required">
</div>
<span id="error_dob" class="text-danger"></span>
</div>
<div class="form-group">
<label for="email" class="cols-sm-2 control-label">Email</label>
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope fa" aria-hidden="true"></i></span>
<input type="text" class="form-control" name="email" id="email" placeholder="Dein Email" data-validation="required" />
</div>
</div>
<span id="error_email" class="text-danger"></span>
</div>
<div class="form-group">
<label for="username" name="username" class="cols-sm-2 control-label username">Benutzername</label>
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-users fa" aria-hidden="true"></i></span>
<input type="text" class="form-control" name="username" id="username" placeholder="Benutzername" data-validation="required" />
</div>
</div>
<span id="error_username" class="text-danger"></span>
</div>
<div class="form-group">
<label for="password" class="cols-sm-2 control-label">Passwort</label>
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-lock fa-lg" aria-hidden="true"></i></span>
<input type="password" class="form-control" name="password" id="password" placeholder="Passwort" data-validation="required" />
</div>
</div>
<span id="error_password" class="text-danger"></span>
</div>
<div class="form-group">
<label for="confirm" class="cols-sm-2 control-label">Bestätigen</label>
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-lock fa-lg" aria-hidden="true"></i></span>
<input type="password" class="form-control" name="confirm" id="confirm" placeholder="Passwort" data-validation="required" />
</div>
</div>
<span id="error_confirm" class="text-danger"></span>
</div>
<div class="form-group ">
<input type="submit" value="Submit" id="submit" class="btn btn-secondary center"/>
</div>
</form>
</div>
</div>
</div>
</body>

For Jquery validation, you need to set data-val=true and data-val-required='Some required error message. Also the jquery unobtrusive plugin makes things work much smoother.
I would recommend looking into as your on code has logic errors. For example, your $("#submit").click should return false if you have validation errors.
As for integrating with the data base, you will need a php handler and you'll use jquery's ajax function $.ajax( to send the fields you want to validate first to the php handler.
You could also submit the form at this point and perform validation on the server side, which you should be doing anyone because anyone can modify your form validation methods, or even have javascript disabled on their browser, and submit invalid data anyway.

Related

How to Change the Color of the Progress Bar with Conditions

I am having a problem with changing or update background color in -webkit-progress-value with the condition.
I'm trying to use :
document.querySelectorAll('progress ::-webkit-progress-value').style.setProperty('background', 'blue');
and using jquery :
$('progress ::-webkit-progress-value').css('background', 'blue');
but the color of the progress bar still the default color (grey).
Any solution to update the color with the condition below?
Bronze: Boy (orange red) & Girl (purple)
Silver: Boy (yellow) & Girl (green)
Gold: Boy (red) & Girl (blue)
function check() {
var classTrophy = "Gold";
if (classTrophy == "Bronze") {
console.log("Bronze");
document.getElementById("boy").style.background = "orangered";
document.getElementById("girl").style.background = "purple";
} else if (classTrophy == "Silver") {
console.log("Silver");
document.getElementById("boy").style.background = "yellow";
document.getElementById("girl").style.background = "green";
} else if (classTrophy == "Gold") {
console.log("Gold");
document.getElementById("boy").style.background = "red";
document.getElementById("girl").style.background = "blue";
}
}
progress {
width: 100%;
-webkit-appearance: none;
margin-left: 8px;
height: 8px;
}
progress::-webkit-progress-value {
-webkit-appearance: none;
background: grey;
white-space: pre;
border-radius: 2px;
box-shadow: 0 2px 5px rgba(249, 255, 249, 0.78) inset;
}
progress::-webkit-progress-bar {
-webkit-appearance: none;
white-space: pre;
background: #ffffff;
border-radius: 2px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.34) inset;
}
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body onload="check()">
<main>
<div class="form-group">
<label for="" class="mb-0" id="boyPoint" style="font-size:12px;color:black">Boy</label>
<div id="boyBar" class="input-group">
<progress id="boy" value="50" max="100"> </progress>
</div>
</div>
<br><br>
<div class="form-group">
<label for="" class="mb-0" id="girlPoint" style="font-size:12px;color:black">Girl</label>
<div id="girlBar" class="input-group">
<progress id="girl" value="80" max="100"> </progress>
</div>
</div>
</div>
</main>
</body>
</html>
Try this
function check() {
var classTrophy = "Gold";
if (classTrophy == "Bronze") {
console.log("Bronze");
document.getElementById("boy").style.background = "orangered";
document.getElementById("girl").style.background = "purple";
} else if (classTrophy == "Silver") {
console.log("Silver");
document.getElementById("boy").classList.add("progress-yellow");
document.getElementById("girl").classList.add("progress-green");
} else if (classTrophy == "Gold") {
console.log("Gold");
document.getElementById("boy").classList.add("progress-red");
document.getElementById("girl").classList.add("progress-blue");
}
}
progress {
width: 100%;
-webkit-appearance: none;
margin-left: 8px;
height: 8px;
}
progress::-webkit-progress-value {
-webkit-appearance: none;
background: grey;
white-space: pre;
border-radius: 2px;
box-shadow: 0 2px 5px rgba(249, 255, 249, 0.78) inset;
}
progress::-webkit-progress-bar {
-webkit-appearance: none;
white-space: pre;
background: #ffffff;
border-radius: 2px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.34) inset;
}
.progress-yellow::-webkit-progress-bar{
background: yellow;
}
.progress-red::-webkit-progress-bar{
background: red;
}
.progress-blue::-webkit-progress-bar{
background: blue;
}
.progress-green::-webkit-progress-bar{
background: green;
}
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body onload="check()">
<main>
<div class="form-group">
<label for="" class="mb-0" id="boyPoint" style="font-size:12px;color:black">Boy</label>
<div id="boyBar" class="input-group">
<progress id="boy" value="50" max="100"> </progress>
</div>
</div>
<br><br>
<div class="form-group">
<label for="" class="mb-0" id="girlPoint" style="font-size:12px;color:black">Girl</label>
<div id="girlBar" class="input-group">
<progress id="girl" value="80" max="100"> </progress>
</div>
</div>
</div>
</main>
</body>
</html>

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>

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

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

FormValidation in Bootstrap is not working

I am making a login and register page. I am implementing form validation also. I want to do something like this- when the page loads first the LOGIN page gets active, when REGISTER is clicked then a register page gets active and display the form.
I have tried doing it over jsfiddle: jsfiddle link. I don't know why the transition effect does not work. It's just a simple transition on the panel-heading:
HTML-
<div class="panel-heading">
<div class="row">
<div class="col-xs-6">
LOGIN
</div>
<div class="col-xs-6">
REGISTER
</div>
</div>
JS-
$(document).ready(function() {
$("#login-form-link").click(function(e) {
$("#login-form").delay(100).fadeIn(100);
$("#register-form").fadeOut(100);
$("#register-form-link").removeClass("active");
$(this).addClass("active");
e.preventDefault();
});
$("#register-form-link").click(function(e) {
$("#register-form").delay(100).fadeIn(100);
$("#login-form").fadeOut(100);
$("#login-form-link").removeClass("active");
$(this).addClass("active");
e.preventDefault();
});
});
After it I am focusing on the validation of the REGISTER form. Believe me the register form opens in my browser I don't know why the register form does not open in jsfiddle!
Please look at the form its like this:
My problem is that the validation is not working and I don't know why. I have looked at many Stack Overflow links (this one was helpful) but none helps now.
you have multiple syntax errors in jQuery code also you are using wrong libraries,
fiddle provided in question used bootstrapValidator library also jqueryValidation lib, these 2 libraries has nothing to do with formValidation
if you checked your browser console log, half of the problems syntax errors e.g
missing multiple commas
wrong use of semi colon
wrong use of inverted commas
can easily be fixed also you can found $(...).formValidation is not a function in console log too means library is missing.
here is the working fiddle
syntax error fixed and correct and required formValidation libraries added
transition effect working
validation of the register form working
$(document).ready(function() {
$("#login-form-link").click(function(e) {
$("#login-form").delay(100).fadeIn(100);
$("#register-form").fadeOut(100);
$("#register-form-link").removeClass("active");
$(this).addClass("active");
e.preventDefault();
});
$("#register-form-link").click(function(e) {
$("#register-form").delay(100).fadeIn(100);
$("#login-form").fadeOut(100);
$("#login-form-link").removeClass("active");
$(this).addClass("active");
e.preventDefault();
});
$('#register-form').formValidation({
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
fullname: {
validators: {
notEmpty: {
message: "Please enter this field"
},
regexp: {
regexp: /^[A-Za-z\s]{1,}[\.]{0,1}[A-Za-z\s]{0,}$/,
message: "full name cannot contain this symbol "
}
}
},
username: {
validators: {
notEmpty: {
message: "Please enter this field"
},
stringLength: {
min: 5,
max: 15,
message: "username must be more than 5 and less than 15 characters long"
},
regexp: {
regexp: /^[a-zA-Z0-9_\.]+$/,
message: 'username can only consist of alphabets, numbers, dot and underscore'
}
}
},
email: {
validators: {
notEmpty: {
message: "Please enter this field"
},
emailAddress: {
message: "invalid email!"
}
}
},
address: {
validators: {
notEmpty: {
message: "Please enter this field"
},
regexp: {
regexp: /^[a-zA-Z0-9\s,\/-]+$/,
message: "invalid symbol!"
}
}
},
pincode: {
validators: {
notEmpty: {
message: "Please enter this field"
},
stringLength: {
min: 6,
max: 6,
message: "invalid pincode!"
},
digits: {
message: "pin code can contain digits only"
}
}
},
phnumber: {
validators: {
notEmpty: {
message: "Please enter this field"
},
stringLength: {
min: 10,
max: 10,
message: "invalid phone number!"
},
digits: {
message: "phone number can contain digits only"
}
}
},
password: {
validators: {
notEmpty: {
message: "Please enter this field"
},
different: {
field: 'username',
message: 'The password cannot be the same as username'
},
identical: {
field: "confirm_password",
message: 'password and its confirm are not the same'
}
}
},
confirm_password: {
validators: {
notEmpty: {
message: "Please enter this field"
},
identical: {
field: "password",
message: 'password and its confirm are not the same'
}
}
}
}
})
.on('success.form.bv', function(e) {
var $form = $(e.target);
var bv = $form.data('bootstrapValidator');
$.post($form.attr('action'), $form.serialize(), function(result) {
console.log(result);
}, 'json');
});
});
body {
padding-top: 90px;
}
.panel-login {
border-style: solid;
border-color: #7B68EE;
-webkit-box-shadow: 1px 2px 3px 1px rgba(0, 0, 0, 0.2);
-moz-box-shadow: 1px 2px 3px 1px rgba(0, 0, 0, 0.2);
box-shadow: 1px 2px 3px 1px rgba(0, 0, 0, 0.2);
}
.panel-login>.panel-heading {
color: #7B68EE;
background-color: #fff;
border-color: #fff;
text-align: center;
}
.panel-login>.panel-heading a {
text-decoration: none;
color: #666;
font-weight: bold;
font-size: 15px;
-webkit-transition: all 0.1s linear;
-moz-transition: all 0.1s linear;
transition: all 0.1s linear;
}
.panel-login>.panel-heading a.active {
color: #7B68EE;
font-size: 18px;
}
.panel-login>.panel-heading hr {
margin-top: 10px;
margin-bottom: 0px;
clear: both;
border: 0;
height: 1px;
background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.15), rgba(0, 0, 0, 0));
background-image: -moz-linear-gradient(left, rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.15), rgba(0, 0, 0, 0));
background-image: -ms-linear-gradient(left, rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.15), rgba(0, 0, 0, 0));
background-image: -o-linear-gradient(left, rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.15), rgba(0, 0, 0, 0));
}
.panel-login input[type="text"],
.panel-login input[type="email"],
.panel-login input[type="password"] {
height: 45px;
border: 1px solid #ddd;
font-size: 16px;
-webkit-transition: all 0.1s linear;
-moz-transition: all 0.1s linear;
transition: all 0.1s linear;
}
.panel-login input:hover,
.panel-login input:focus {
outline: none;
-webkit-box-shadow: none;
-moz-box-shadow: none;
box-shadow: none;
border-color: #ccc;
}
input[type="submit"].btn-login {
background-color: #59B2E0;
outline: none;
color: #fff;
font-size: 14px;
height: auto;
font-weight: normal;
padding: 14px 0;
text-transform: uppercase;
border-color: #59B2E6;
}
input[type="submit"].btn-login:hover,
input[type="submit"].btn-login:focus {
color: #fff;
background-color: #53A3CD;
border-color: #53A3CD;
}
.forgot-password {
text-decoration: underline;
color: #888;
}
.forgot-password:hover,
.forgot-password:focus {
text-decoration: underline;
color: #666;
}
input[type="submit"].btn-register {
background-color: #59B2E0;
outline: none;
color: #fff;
font-size: 14px;
height: auto;
font-weight: normal;
padding: 14px 0;
text-transform: uppercase;
border-color: #59B2E6;
}
input[type="submit"].btn-register:hover,
input[type="submit"].btn-register:focus {
color: #fff;
background-color: #53A3CD;
border-color: #53A3CD;
}
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.formvalidation/0.6.1/js/formValidation.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.formvalidation/0.6.1/js/framework/bootstrap.min.js"></script>
<div class="container" style="margin-bottom: 5%;">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-login">
<div class="panel-heading">
<div class="row">
<div class="col-xs-6">
LOGIN
</div>
<div class="col-xs-6">
REGISTER
</div>
</div>
<hr>
</div>
<div class="panel-body">
<div class="row">
<div class="col-lg-12">
<form id="login-form" action="/login" method="post" role="form" style="display: block;">
<div class="form-group">
<input type="text" name="username" pattern="^[_A-z0-9]{1,}$" maxlength="15" id="username" tabindex="1" class="form-control" placeholder="username" value="" required>
<!--error message like: "username already exist" -->
<span><p><!--error message here--></p></span>
</div>
<div class="form-group">
<input type="password" name="password" data-minlength="6" id="inputPassword" tabindex="1" class="form-control" placeholder="password" value="" required>
<!--error message like: "username and password do not match" -->
<span><p><!--error message here--></p></span>
</div>
<div class="form-group text-center">
<input type="checkbox" tabindex="3" name="remember" id="remember">
<label for="remember">Remember me</label>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<input type="submit" name="login-submit" id="login-submit" tabindex="4" class="form-control btn btn-login" value="Log in">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-lg-12">
<div class="text-center">
Forgot Password?
</div>
</div>
</div>
</div>
</form>
<form id="register-form" action="/register" method="post" role="form" style="display: none;">
<!-- username -->
<div class="form-group">
<input type="text" name="username" id="username" tabindex="1" class="form-control" placeholder="username" value="" required>
</div>
<!-- email -->
<div class="form-group">
<input type="email" name="email" id="Email" tabindex="1" class="form-control" placeholder="email" value="" data-error="Email address is invalid" required>
</div>
<!-- fullname -->
<div class="form-group">
<input type="text" name="fullname" id="Name" tabindex="1" class="form-control" placeholder="full name" value="" required>
</div>
<!-- address -->
<div class="form-group">
<input type="text" name="address" id="address" tabindex="1" class="form-control" placeholder="address" value="" required>
</div>
<!-- pincode -->
<div class="form-group">
<input type="text" name="pincode" id="pincode" tabindex="1" class="form-control" placeholder="pincode" value="" data-error="Invalid Pin code!" required>
</div>
<!-- phone number -->
<div class="form-group">
<input type="text" name="phnumber" id="phnumber" tabindex="1" class="form-control" placeholder="phone number" value="" data-error="Invalid Phone Number!" required>
</div>
<!-- password -->
<div class="form-group">
<input type="password" name="password" id="inputPassword" tabindex="1" class="form-control" placeholder="password" value="" required>
</div>
<!-- confirm password -->
<div class="form-group">
<input type="password" name="confirm_password" id="confirmPassword" tabindex="1" class="form-control" placeholder="confirm password" value="" required>
</div>
<!-- register button -->
<div class="form-group">
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<input type="submit" name="register-submit" id="register-submit" tabindex="4" class="form-control btn btn-register" value="Register Now">
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>

How to display button when all input field has some value using Angular.js

i need one help.I need to display my button while all input has some value using Angular.js.Let me to explain my code below.
<div class="input-group bmargindiv1 col-md-12">
<span class="input-group-addon ndrftextwidth text-right" style="width:180px">Product Name :</span>
<select class="form-control" id="pro_name" ng-model="pro_name" ng-change="removeBorder('pro_name');" ng-readonly="periodread" >
<option value="">Select Product</option>
<option value="1">Britania</option>
<option value="0">Soap/option>
</select>
</div>
<div class="input-group bmargindiv1 col-md-12">
<span class="input-group-addon ndrftextwidth text-right" style="width:180px">Unit Cost Price :</span>
<input type="text" name="discount" id="ucp" class="form-control" placeholder="Add unit cost price" ng-model="unit_cost_price" ng-keypress="clearField('ucp');" ng-readonly="isChecked=='false'">
</div>
<div class="input-group bmargindiv1 col-md-12">
<span class="input-group-addon ndrftextwidth text-right" style="width:180px">Unit Sale Price :</span>
<input type="text" name="discount" id="usp" class="form-control" placeholder="Add unit sale price" ng-model="unit_sale_price" ng-keypress="clearField('usp');" ng-readonly="isChecked=='false'">
</div>
<div class="input-group bmargindiv1 col-md-12">
<span class="input-group-addon ndrftextwidth text-right" style="width:180px">Quantity :</span>
<input type="text" name="discount" id="quantity" class="form-control" placeholder="Add quantity" ng-model="quantity" ng-keypress="clearField('quantity');">
</div>
<div class="input-group bmargindiv1 col-md-12" ng-show="displayRadio">
<input type="radio" name="favoriteColors" ng-model="isChecked" value="true">Add new stock
<input type="radio" name="favoriteColors" ng-model="isChecked" value="false">Update stock
</div>
<input type="button" class="btn btn-success" ng-click="addProductstockData(billdata);" id="addProfileData" ng-value="buttonName" ng-show="showAddButton"/>
In the code i need when all field has some value the button will display to user.User can also type/select the value in input field and for some cases values are also appending inside input field bu another button click.So here i need when user has any value inside the input fields then only button will display to user.Please help me.
Here`s the working plunker! of your code.
All you need to do is wrap up the inputs in the <form name="theForm" novalidate></form> and give required attribute to inputs and show the button only once the required fields has some value in it, like <button ng-show="theForm.$valid"></button>. Hope that helps
var app = angular.module('form-example', []);
app.directive('passwordValidate', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift(function(viewValue) {
scope.pwdValidLength = (viewValue && viewValue.length >= 8 ? 'valid' : undefined);
scope.pwdHasLetter = (viewValue && /[A-z]/.test(viewValue)) ? 'valid' : undefined;
scope.pwdHasNumber = (viewValue && /\d/.test(viewValue)) ? 'valid' : undefined;
if(scope.pwdValidLength && scope.pwdHasLetter && scope.pwdHasNumber) {
ctrl.$setValidity('pwd', true);
return viewValue;
} else {
ctrl.$setValidity('pwd', false);
return undefined;
}
});
}
};
});
.input-help {
display: none;
position:absolute;
z-index: 100;
top: -6px;
left: 160px;
width:200px;
padding:10px;
background:#fefefe;
font-size:.875em;
border-radius:5px;
box-shadow:0 1px 3px #aaa;
border:1px solid #ddd;
opacity: 0.9;
}
.input-help::before {
content: "\25C0";
position: absolute;
top:10px;
left:-12px;
font-size:16px;
line-height:16px;
color:#ddd;
text-shadow:none;
}
.input-help h4 {
margin:0;
padding:0;
font-weight: normal;
font-size: 1.1em;
}
/* Always hide the input help when it's pristine */
input.ng-pristine + .input-help {
display: none;
}
/* Hide the invalid box while the input has focus */
.ng-invalid:focus + .input-help {
display: none;
}
/* Show a blue border while an input has focus, make sure it overrides everything else */
/* Overriding Twitter Bootstrap cuz I don't agree we need to alarm the user while they're typing */
input:focus {
color: black !important;
border-color: rgba(82, 168, 236, 0.8) !important;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6) !important;
-moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6) !important;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6) !important;
}
/* Show green border when stuff has been typed in, and its valid */
.ng-dirty.ng-valid {
border-color:#3a7d34;
}
/* Show red border when stuff has been typed in, but its invalid */
.ng-dirty.ng-invalid {
border-color:#ec3f41;
}
/* Show the help box once it has focus */
.immediate-help:focus + .input-help {
display: block;
}
/* Immediate help should be red when pristine */
.immediate-help.ng-pristine:focus + .input-help {
border-color:#ec3f41;
}
.immediate-help.ng-pristine:focus + .input-help::before {
color:#ec3f41;
}
/* Help hould be green when input is valid */
.ng-valid + .input-help {
border-color:#3a7d34;
}
.ng-valid + .input-help::before {
color:#3a7d34;
}
/* Help should show and be red when invalid */
.ng-invalid + .input-help {
display: block;
border-color: #ec3f41;
}
.ng-invalid + .input-help::before {
color: #ec3f41;
}
/* Style input help requirement bullets */
.input-help ul {
list-style: none;
margin: 10px 0 0 0;
}
/* Default each bullet to be invalid with a red cross and text */
.input-help li {
padding-left: 22px;
line-height: 24px;
color:#ec3f41;
background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAA1CAYAAABIkmvkAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAAJwAAACcBKgmRTwAAABZ0RVh0Q3JlYXRpb24gVGltZQAxMC8wOS8xMlhq+BkAAAAcdEVYdFNvZnR3YXJlAEFkb2JlIEZpcmV3b3JrcyBDUzVxteM2AAAEA0lEQVRIie2WW2jbVRzHv//zT5rkn0ub61zaNdEiPqTC9EFRhtgJk63qg3Wr0806pswNiYgDUXxwyryCEB8UBevtaSCCDHQoboKyoVvVzfRmL2napU0mrdbl8s//dy4+dM1M28n64FsPnIdz+XzO75zfOXA0pRRWU7o/uS9FxOc+3/vlIQBgq4F3fHxvKuIPJ9cFwi9uTXU8BwDa1Uaw/aN7UusCkWRbPI5yxcTI2Bgy49kXrkrwwIedqYg/nGyLXwsJiYHBYWTGs7Cq5Kpt4cA3PXft+2rX40vhrt7OVLgplIzHYuBKoH9gCKMjGVE1LdfJl86YDAAOfN2ziZP4NODyv9/z2fanFuH7P9iWCjcFk/FYK4QSGLgEk0WeUy/3mQCgPXFs9xbBRW883NrssDvQN3hWcOLPEPGWiD94MBaPQymBoaERjI9mBSfu+fHwL+biItpjR3e6JFfloDeAaGQ9SpUycvlp6ExHJBKGYsDvgyMYH81KTsL90yuX4VoWdh3pMqSQpWBjAC3RZkgpYEkCFDA8NIqJ0UlFxI3Tr/5aB9elsau305BcloKBAFpjLeBSYGRwDBNjk4oTN06/dnYZXCcAgK1vbzYkl6VwOATihOzYlOLEjTOvn1sRXiYAgDsP32YIKUuWaXFOwtP3xrnqleAVBQBwy/M3GZy4+PnN3/4TvqJgNWVVj2lNsCZYE6wJ1gRrgv9dYAMAHHw2Bl2fUEpBVavtLPVW/78nVR/Zk4CupzVHA6zChSOK0yHv0S8GFyK4BMPhAJxOgLE03/9kYhE2dz+agKaldY8bDaEQ7D5ft7Roy+UIlCooy5LQdaZ5vVBEgGmmrT172yVxaIylmdcDm9cHc2oK1Zm8kETvLAo0pRRk8mmnEqKouVw68zVCzP8F/uccFHHoXi/sjT6Y53Mw83mhOHn8J7416wQAwPftd0ouiswwdJu/CRASkBKQAmYuBzNfWIC/O173W6llwfbeu6Yi8tDsrAQJYGICyGQAIWDO5KUkaxlcJwAASdSmaWAQHCACOAc4h6YzJi1qWymNNUHlwYcT0JDWXQbACYhGgeh6gHM4Ghuh2/R0YePNiaUCTSmFcvdDCY1paZvhht3nQ2VmGmahICSR5vQHmDt6DcozeZSnp2FdLLZHhwdq94SVd+xMaJqWtrkM2L1uVHILpy0t8igidymXExfHMzBCQbhCIdga7Onz8etqkdgkUYTZbYCSqORmULlQEIq4J3jyexMA8jdu9BRzuaKyLN3udkNjDEqICID+2hbm797Wwez24/T3vJTE3aFTP9Sd9vT1NziVEMUGr1c35+Y2b5jKnqgNKqWglMLspjs6/rj1dudie2mdao07J5s3dCzt/werJTyI1yYqpQAAAABJRU5ErkJggg==) no-repeat 2px -34px;
}
/* Set to green check and text when valid */
.input-help li.valid {
color:#3a7d34;
background-position: 2px 6px;
}
/* Set submit button */
form .btn, form.ng-valid .btn[disabled] {
display: none;
}
form.ng-invalid .btn[disabled], form.ng-valid .btn {
display: inline-block;
}
body {
padding: 20px 0;
}
input {
width: 166px
}
.form-horizontal .control-label {
width: 100px;
}
.form-horizontal .controls {
position: relative;
margin-left: 120px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form ng-app="form-example" class="row form-horizontal" novalidate>
<div class="control-group">
<label class="control-label" for="inputEmail">Email</label>
<div class="controls">
<input type="email" id="inputEmail" placeholder="Email" ng-model="email" required>
<div class="input-help">
<h4>Invalid Email</h4>
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Password</label>
<div class="controls">
<input ng-model="password" class="immediate-help" password-validate required type="password" id="inputPassword" placeholder="Password">
<div class="input-help">
<h4>Password must meet the following requirements:</h4>
<ul>
<li ng-class="pwdHasLetter">At least <strong>one letter</strong></li>
<li ng-class="pwdHasNumber">At least <strong>one number</strong></li>
<li ng-class="pwdValidLength">At least <strong>8 characters long</strong></li>
</ul>
</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn">Create Account</button>
<button class="btn" disabled>Create Account</button>
</div>
</div>
</form>

Categories