Disable button untill all fields are cleared - javascript

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>

Related

Collecting information from a step-form and displaying it in a confirmation page?

In the snippet below, I have a step-form. While submitting the content in the form and hitting next, the input values are being passed to the confirmation page at the end.
I'm trying to understand if this is the most efficient way to pass the information to the confirmation page?
const previousButton = document.getElementById("previous")
const nextButton = document.getElementById("next")
const submitButton = document.getElementById('validate')
const form = document.getElementById('stepByStepForm')
const dots = document.getElementsByClassName('progress-bar__dot')
const numberOfSteps = 5
let currentStep = 1
for(let i = 0 ; i < dots.length ; ++i){
dots[i].addEventListener('click', ()=>{
goToStep(i+1)
})
}
previousButton.onclick = goPrevious
nextButton.onclick = goNext
function goNext(e) {
e.preventDefault()
currentStep += 1
goToStep(currentStep)
}
function goPrevious(e) {
e.preventDefault()
currentStep -= 1
goToStep(currentStep)
}
function goToStep(stepNumber){
currentStep = stepNumber
let inputsToHide = document.getElementsByClassName('step')
let inputs = document.getElementsByClassName(`step${currentStep}`)
let indicators = document.getElementsByClassName('progress-bar__dot')
for(let i = indicators.length-1; i >= currentStep ; --i){
indicators[i].classList.remove('full')
}
for(let i = 0; i < currentStep; ++i){
indicators[i].classList.add('full')
}
//hide all input
for (let i = 0; i < inputsToHide.length; ++i) {
hide(inputsToHide[i])
}
//only show the right one
for (let i = 0; i < inputs.length; ++i) {
show(inputs[i])
}
//if we reached final step
if(currentStep === numberOfSteps){
enable(previousButton)
disable(nextButton)
show(submitButton)
}
//else if first step
else if(currentStep === 1){
disable(previousButton)
enable(next)
hide(submitButton)
}
else {
enable(previousButton)
enable(next)
hide(submitButton)
}
}
function enable(elem) {
elem.classList.remove("disabled");
elem.disabled = false;
}
function disable(elem) {
elem.classList.add("disabled");
elem.disabled = true;
}
function show(elem){
elem.classList.remove('hidden')
}
function hide(elem){
elem.classList.add('hidden')
}
//collect inputs
next.addEventListener('click', function() {
const fNameInput = document.getElementById('firstname').value;
document.getElementById('fNameOutput').textContent = fNameInput;
const lNameInput = document.getElementById('lastname').value;
document.getElementById('lNameOutput').textContent = lNameInput;
const emailInput = document.getElementById('mail').value;
document.getElementById('emailOutput').textContent = emailInput;
const phoneInput = document.getElementById('phone').value;
document.getElementById('phoneOutput').textContent = phoneInput;
const addressInput = document.getElementById('address').value;
document.getElementById('addressOutput').textContent = addressInput;
const countryInput = document.getElementById('country').value;
document.getElementById('countryOutput').textContent = countryInput;
const colorInput = document.getElementById('color').value;
document.getElementById('colorOutput').textContent = colorInput;
const animalInput = document.getElementById('animal').value;
document.getElementById('animalOutput').textContent = animalInput;
});
submitButton.addEventListener('click', function(e) {
e.preventDefault();
})
html {
background-color: #A2C7E5;
}
.hidden {
display: none;
}
.button {
width: 140px;
cursor: pointer;
padding: 1em;
border-radius: 0.2em;
border: none;
color: white;
font-weight: bold;
font-size: 1em;
transition: all 0.5s ease;
background-color: #ff8552;
}
.button:hover {
background-color: #ff4f06;
}
.button.disabled {
opacity: 0.5;
}
.button.disabled:hover {
background-color: #ff8552;
}
.form {
width: 20em;
margin: auto;
margin-top: 5em;
padding: 5em;
padding-top: 2em;
padding-bottom: 2em;
background-color: white;
font-family: "Raleway", sans-serif;
color: #33312E;
border-radius: 0.2em;
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19), 0 6px 6px rgba(0, 0, 0, 0.23);
}
.form .progress-bar {
width: 100%;
list-style-type: none;
display: flex;
padding: 0;
justify-content: center;
margin-bottom: 3.5em;
}
.form .progress-bar li.progress-bar__dot {
display: block;
width: 0.6em;
border-radius: 50%;
height: 0.6em;
border: 0.1em solid #ff8552;
background-color: white;
cursor: pointer;
transition: all 0.5s ease;
}
.form .progress-bar li.progress-bar__dot.full {
background-color: #ff8552;
}
.form .progress-bar li.progress-bar__connector {
display: block;
width: 5em;
border-radius: 1000em;
height: 0.1em;
background-color: #ff8552;
margin-top: 0.35em;
}
.form label {
font-weight: bold;
font-size: 1.2em;
}
.form input {
width: 100%;
padding: 1.3em;
margin-bottom: 3em;
box-sizing: border-box;
margin-top: 1em;
border: none;
border-radius: 0.5em;
background-color: #e6e6e6;
font-size: 1em;
font-family: "Raleway", sans-serif;
}
.form input:focus {
border: none;
}
.form .button-group {
width: 100%;
display: flex;
justify-content: space-between;
margin-top: 50px;
}
.form button#validate {
margin: auto;
background-color: #1A936F;
width: 12em;
}
.form button#validate:hover {
background-color: #12684e;
}
<form id="stepByStepForm" class="form">
<ul class="progress-bar">
<li class="progress-bar__dot full"></li>
<li class="progress-bar__connector"></li>
<li class="progress-bar__dot"></li>
<li class="progress-bar__connector"></li>
<li class="progress-bar__dot"></li>
<li class="progress-bar__connector"></li>
<li class="progress-bar__dot"></li>
<li class="progress-bar__connector"></li>
<li class="progress-bar__dot"></li>
</ul>
<div class="step step1">
<div class="input-group">
<label for="firstname">First name</label>
<input type="text" value="James" name="firstname" id="firstname">
</div>
<div class="input-group">
<label for="lastname">Last name</label>
<input type="text" value="Smith" name="lastname" id="lastname">
</div>
</div>
<div class="step step2 hidden">
<div class="input-group">
<label for="mail">E-mail</label>
<input type="mail" value="jamessmith#gmail.com" name="mail" id="mail">
</div>
<div class="input-group">
<label for="phone">Phone</label>
<input type="text" value="602-379-1395" name="phone" id="phone">
</div>
</div>
<div class="step step3 hidden">
<div class="input-group">
<label for="address">Address</label>
<input type="text" value="221B Baker Street" name="address" id="address">
</div>
<div class="input-group">
<label for="country">Country</label>
<input type="text" value="United States" name="country" id="country">
</div>
</div>
<div class="step step4 hidden">
<div class="input-group">
<label for="color">Favorite Color</label>
<input type="text" value="Blue" name="color" id="color">
</div>
<div class="input-group">
<label for="animal">Favorite Animal</label>
<input type="text" value="Lion" name="animal" id="animal">
</div>
</div>
<div class="step step5 hidden">
<h4>Name:</h4>
<p><strong>First Name:</strong> <span id="fNameOutput"></span></p>
<p><strong>Last Name:</strong> <span id="lNameOutput"></span></p>
<hr>
<h4>Contact:</h4>
<p><strong>Email:</strong> <span id="emailOutput"></span></p>
<p><strong>Phone:</strong> <span id="phoneOutput"></span></p>
<hr>
<h4>Location:</h4>
<p><strong>Address:</strong> <span id="addressOutput"></span></p>
<p><strong>Country:</strong> <span id="countryOutput"></span></p>
<hr>
<h4>Attributes:</h4>
<p><strong>Favorite Color:</strong> <span id="colorOutput"></span></p>
<p><strong>Favorite Animal:</strong> <span id="animalOutput"></span></p>
</div>
<div class="button-group">
<button id="previous" class="disabled button" disabled>
previous
</button>
<button id="next" class="button">
next
</button>
</div>
<div class="button-group">
<button id="validate" type="submit" class="hidden button">
Submit
</button>
</div>
</form>
There are 3 problems:
In this part next.addEventListener('click', function() {...}, it updates all texts every time the next button is pressed.
document.getElementById(ID_NAME).textContent = VALUE; is written repeatedly; It is not that bad but there are more readable ways.
The confirmation textContents are not updated when the last dot is clicked.
First, make a function to update texts. To avoid writing similar code repeatedly, you can use an Object for ids and for...of to implement updating the text contents.
function updateConfirmText() {
const map = {
firstname: 'fNameOutput',
lastname: 'lNameOutput',
mail: 'emailOutput',
phone: 'phoneOutput',
address: 'addressOutput',
country: 'countryOutput',
color: 'colorOutput',
animal: 'animalOutput'
};
for (const [input, output] of Object.entries(map)) {
document.getElementById(output).textContent = document.getElementById(input).value;
}
}
Second, call the function in the if statement that you have already written.
//if we reached final step
if (currentStep === numberOfSteps) {
enable(previousButton)
disable(nextButton)
show(submitButton)
updateConfirmText(); // Add
}
I hope it works🤞

How to use javascript to detect whether there is a value in the input box that contains a blank string, and if so, make the button clickable [duplicate]

I have this input field
<input name="question"/> I want to call IsEmpty function when submit clicking submit button.
I tried the code below but did not work.
any advice?
function IsEmpty() {
if (document.form.question.value == "") {
alert("empty");
}
return;
}
Question: <input name="question" /> <br/>
<input id="insert" onclick="IsEmpty();" type="submit" value="Add Question" />
<script type="text/javascript">
function validateForm() {
var a = document.forms["Form"]["answer_a"].value;
var b = document.forms["Form"]["answer_b"].value;
var c = document.forms["Form"]["answer_c"].value;
var d = document.forms["Form"]["answer_d"].value;
if ((a == null || a == "") && (b == null || b == "") && (c == null || c == "") && (d == null || d == "")) {
alert("Please Fill In All Required Fields");
return false;
}
}
</script>
<form method="post" name="Form" onsubmit="return validateForm()" action="">
<textarea cols="30" rows="2" name="answer_a" id="a"></textarea>
<textarea cols="30" rows="2" name="answer_b" id="b"></textarea>
<textarea cols="30" rows="2" name="answer_c" id="c"></textarea>
<textarea cols="30" rows="2" name="answer_d" id="d"></textarea>
</form>
An input field can have whitespaces, we want to prevent that.
Use String.prototype.trim():
function isEmpty(str) {
return !str.trim().length;
}
Example:
const isEmpty = str => !str.trim().length;
document.getElementById("name").addEventListener("input", function() {
if( isEmpty(this.value) ) {
console.log( "NAME is invalid (Empty)" )
} else {
console.log( `NAME value is: ${this.value}` );
}
});
<input id="name" type="text">
See the working example here
You are missing the required <form> element. Here is how your code should be like:
function IsEmpty() {
if (document.forms['frm'].question.value === "") {
alert("empty");
return false;
}
return true;
}
<form name="frm">
Question: <input name="question" /> <br />
<input id="insert" onclick="return IsEmpty();" type="submit" value="Add Question" />
</form>
I would like to add required attribute in case user disabled javascript:
<input type="text" id="textbox" required/>
It works on all modern browsers.
if(document.getElementById("question").value.length == 0)
{
alert("empty")
}
Add an id "question" to your input element and then try this:
if( document.getElementById('question').value === '' ){
alert('empty');
}
The reason your current code doesn't work is because you don't have a FORM tag in there. Also, lookup using "name" is not recommended as its deprecated.
See #Paul Dixon's answer in this post : Is the 'name' attribute considered outdated for <a> anchor tags?
You can loop through each input after submiting and check if it's empty
let form = document.getElementById('yourform');
form.addEventListener("submit", function(e){ // event into anonymous function
let ver = true;
e.preventDefault(); //Prevent submit event from refreshing the page
e.target.forEach(input => { // input is just a variable name, e.target is the form element
if(input.length < 1){ // here you're looping through each input of the form and checking its length
ver = false;
}
});
if(!ver){
return false;
}else{
//continue what you were doing :)
}
})
<script type="text/javascript">
function validateForm() {
var a = document.forms["Form"]["answer_a"].value;
var b = document.forms["Form"]["answer_b"].value;
var c = document.forms["Form"]["answer_c"].value;
var d = document.forms["Form"]["answer_d"].value;
if (a == null || a == "", b == null || b == "", c == null || c == "", d == null || d == "") {
alert("Please Fill All Required Field");
return false;
}
}
</script>
<form method="post" name="Form" onsubmit="return validateForm()" action="">
<textarea cols="30" rows="2" name="answer_a" id="a"></textarea>
<textarea cols="30" rows="2" name="answer_b" id="b"></textarea>
<textarea cols="30" rows="2" name="answer_c" id="c"></textarea>
<textarea cols="30" rows="2" name="answer_d" id="d"></textarea>
</form>
if(document.getElementById("question").value == "")
{
alert("empty")
}
Just add an ID tag to the input element... ie:
and check the value of the element in you javascript:
document.getElementById("question").value
Oh ya, get get firefox/firebug. It's the only way to do javascript.
Customizing the input message using HTML validation when clicking on Javascript button
function msgAlert() {
const nameUser = document.querySelector('#nameUser');
const passUser = document.querySelector('#passUser');
if (nameUser.value === ''){
console.log('Input name empty!');
nameUser.setCustomValidity('Insert a name!');
} else {
nameUser.setCustomValidity('');
console.log('Input name ' + nameUser.value);
}
}
const v = document.querySelector('.btn-petroleo');
v.addEventListener('click', msgAlert, false);
.container{display:flex;max-width:960px;}
.w-auto {
width: auto!important;
}
.p-3 {
padding: 1rem!important;
}
.align-items-center {
-ms-flex-align: center!important;
align-items: center!important;
}
.form-row {
display: -ms-flexbox;
display: flex;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
margin-right: -5px;
margin-left: -5px;
}
.mb-2, .my-2 {
margin-bottom: .5rem!important;
}
.d-flex {
display: -ms-flexbox!important;
display: flex!important;
}
.d-inline-block {
display: inline-block!important;
}
.col {
-ms-flex-preferred-size: 0;
flex-basis: 0;
-ms-flex-positive: 1;
flex-grow: 1;
max-width: 100%;
}
.mr-sm-2, .mx-sm-2 {
margin-right: .5rem!important;
}
label {
font-family: "Oswald", sans-serif;
font-size: 12px;
color: #007081;
font-weight: 400;
letter-spacing: 1px;
text-transform: uppercase;
}
label {
display: inline-block;
margin-bottom: .5rem;
}
.x-input {
background-color: #eaf3f8;
font-family: "Montserrat", sans-serif;
font-size: 14px;
}
.login-input {
border: none !important;
width: 100%;
}
.p-4 {
padding: 1.5rem!important;
}
.form-control {
display: block;
width: 100%;
height: calc(1.5em + .75rem + 2px);
padding: .375rem .75rem;
font-size: 1rem;
font-weight: 400;
line-height: 1.5;
color: #495057;
background-color: #fff;
background-clip: padding-box;
border: 1px solid #ced4da;
border-radius: .25rem;
transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;
}
button, input {
overflow: visible;
margin: 0;
}
.form-row {
display: -ms-flexbox;
display: flex;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
margin-right: -5px;
margin-left: -5px;
}
.form-row>.col, .form-row>[class*=col-] {
padding-right: 5px;
padding-left: 5px;
}
.col-lg-12 {
-ms-flex: 0 0 100%;
flex: 0 0 100%;
max-width: 100%;
}
.mt-1, .my-1 {
margin-top: .25rem!important;
}
.mt-2, .my-2 {
margin-top: .5rem!important;
}
.mb-2, .my-2 {
margin-bottom: .5rem!important;
}
.btn:not(:disabled):not(.disabled) {
cursor: pointer;
}
.btn-petroleo {
background-color: #007081;
color: white;
font-family: "Oswald", sans-serif;
font-size: 12px;
text-transform: uppercase;
padding: 8px 30px;
letter-spacing: 2px;
}
.btn-xg {
padding: 20px 100px;
width: 100%;
display: block;
}
.btn {
display: inline-block;
font-weight: 400;
color: #212529;
text-align: center;
vertical-align: middle;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
background-color: transparent;
border: 1px solid transparent;
padding: .375rem .75rem;
font-size: 1rem;
line-height: 1.5;
border-radius: .25rem;
transition: color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;
}
input {
-webkit-writing-mode: horizontal-tb !important;
text-rendering: auto;
color: -internal-light-dark(black, white);
letter-spacing: normal;
word-spacing: normal;
text-transform: none;
text-indent: 0px;
text-shadow: none;
display: inline-block;
text-align: start;
appearance: textfield;
background-color: -internal-light-dark(rgb(255, 255, 255), rgb(59, 59, 59));
-webkit-rtl-ordering: logical;
cursor: text;
margin: 0em;
font: 400 13.3333px Arial;
padding: 1px 2px;
border-width: 2px;
border-style: inset;
border-color: -internal-light-dark(rgb(118, 118, 118), rgb(195, 195, 195));
border-image: initial;
}
<div class="container">
<form name="myFormLogin" class="w-auto p-3 mw-10">
<div class="form-row align-items-center">
<div class="col w-auto p-3 h-auto d-inline-block my-2">
<label class="mr-sm-2" for="nameUser">Usuário</label><br>
<input type="text" class="form-control mr-sm-2 x-input login-input p-4" id="nameUser"
name="nameUser" placeholder="Name" required>
</div>
</div>
<div class="form-row align-items-center">
<div class="col w-auto p-3 h-auto d-inline-block my-2">
<label class="mr-sm-2" for="passUser">Senha</label><br>
<input type="password" class="form-control mb-3 mr-sm-2 x-input login-input p-4" id="passUser"
name="passUser" placeholder="Password" required>
<div class="help">Esqueci meu usuário ou senha</div>
</div>
</div>
<div class="form-row d-flex align-items-center">
<div class="col-lg-12 my-1 mt-2 mb-2">
<button type="submit" value="Submit" class="btn btn-petroleo btn-lg btn-xg btn-block p-4">Entrar</button>
</div>
</div>
<div class="form-row align-items-center d-flex">
<div class="col-lg-12 my-1">
<div class="nova-conta">Ainda nĂŁo Ă© cadastrado? Crie seu acesso</div>
</div>
</div>
</form>
</div>
My solution below is in es6 because I made use of const if you prefer es5 you can replace all const with var.
const str = " Hello World! ";
// const str = " ";
checkForWhiteSpaces(str);
function checkForWhiteSpaces(args) {
const trimmedString = args.trim().length;
console.log(checkStringLength(trimmedString))
return checkStringLength(trimmedString)
}
// If the browser doesn't support the trim function
// you can make use of the regular expression below
checkForWhiteSpaces2(str);
function checkForWhiteSpaces2(args) {
const trimmedString = args.replace(/^\s+|\s+$/gm, '').length;
console.log(checkStringLength(trimmedString))
return checkStringLength(trimmedString)
}
function checkStringLength(args) {
return args > 0 ? "not empty" : "empty string";
}
<pre>
<form name="myform" action="saveNew" method="post" enctype="multipart/form-data">
<input type="text" id="name" name="name" />
<input type="submit"/>
</form>
</pre>
<script language="JavaScript" type="text/javascript">
var frmvalidator = new Validator("myform");
frmvalidator.EnableFocusOnError(false);
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("name", "req", "Plese Enter Name");
</script>
before using above code you have to add the gen_validatorv31.js file
Combining all the approaches we can do something like this:
const checkEmpty = document.querySelector('#checkIt');
checkEmpty.addEventListener('input', function () {
if (checkEmpty.value && // if exist AND
checkEmpty.value.length > 0 && // if value have one charecter at least
checkEmpty.value.trim().length > 0 // if value is not just spaces
)
{ console.log('value is: '+checkEmpty.value);}
else {console.log('No value');
}
});
<input type="text" id="checkIt" required />
Note that if you truly want to check values you should do that on the server, but this is out of the scope for this question.
The following code worked for me perfectly:
<form action = "dashboard.php" onsubmit= "return someJsFunction()">
<button type="submit" class="button" id = "submit" name="submit" >Upload to live listing</button>
</form>
<script type="text/javascript">
function someJsFunction(){
const input = document.getElementById('input1');
if(input.value === ""){
alert ("no input?"); // This will prevent the Form from submitting
return false;
}else{
return true; // this will submit the form and handle the control to php.
}
}
</script>

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:

Form not going into validation function onsubmit

This is a signup form, after inputting all the values, the validation()must validate the inputs and if all inputs are valid, should be redirected to home page, but my form is not entering the Javascript validation on submitting the form.
This is my code:
<!DOCTYPE html>
<html><head>
<style>
body {font-family: Arial, Helvetica, sans-serif;
background-color: black;}
* {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: #C0C0C0;
}
input[type=text]:focus, input[type=password]:focus {
background-color: #ffbf00;
outline: none;
}
hr {
border: 1px solid #000000;
margin-bottom: 25px;
}
/* Set a style for all buttons */
button {
background-color: #4CAF50;
color: darkgreen;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 50%;
opacity: 0.9;
}
button:hover {
opacity:1;
}
/* Extra styles for the cancel button */
.cancelbtn {
padding: 14px 20px;
background-color: #f44336;
}
/* Add padding to container elements */
.container {
padding: 16px;
background-color: white;
}
/* Clear floats */
.clearfix::after {
content: "";
clear: both;
display: table;
}
.signupbtn {
width: 50%;
}
</style>
<script type="text/javascript">
function validation() {
alert('in..');
var uname = document.signup_form.username.value;
var mail= document.signup_form.email.value;
var num= document.signup_form.phone.value;
var pass= document.signup_form.psw.value;
var des= document.signup_form.desg.value;
alert('validating...');
if allLetter(uname){
if ValidateEmail(mail){
if check_phonenumber(num){
if CheckPassword(pass){
if desgselect(des){
}
}
}
}
}
return false;
}
function allLetter(uname)
{
alert('validating username');
var letters = /^[A-Za-z]+$/;
if(uname.value.match(letters))
{
alert('corret name');
return true;
}
else
{
alert('Username must have alphabet characters only');
uname.focus();
return false;
}
}
function ValidateEmail(mail)
{
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(signup_form.email.value))
{
alert('valid mail ID');
return (true)
}
alert("You have entered an invalid email address!");
return (false)
}
function check_phonenumber(num)
{
var phoneno = /^\d{10}$/;
if((num.value.match(phoneno))
{
alert('valid phone number');
return true;
}
else
{
alert("invalid phone number");
return false;
}
}
function CheckPassword(pass)
{
var passw= /^[A-Za-z]\w{7,15}$/;
if(pass.value.match(passw))
{
alert('Correct, try another...');
return true;
}
else
{
alert('Wrong...!');
return false;
}
}
function desgselect(des)
{
if(des.value == "Default")
{
alert('Select your designation from the list');
desg.focus();
return false;
}
else
{
alert('selected correct designation');
return true;
}
}
//}
</script>
</head>
<body>
<form name="signup_form" onsubmit="return validation()" action="main.html" method="post" style="border:1px solid #ccc">
<div class="container">
<h1><center>Sign Up</center></h1>
<p><center>Please fill in this form to create an account.</center></p>
<hr>
<label for="username"><b>Name</b></label>
<input type="text" placeholder="Enter your full name" name="username" required>
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" required>
<label for="phone"><b>Phone</b></label>
<input type="text" id="phone" name="phone" placeholder="Enter your mobile number" required><br>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<label for="desg"><b>Designation</b></label>
<select name="desg">
<option selected="" value="Default">(Please select your designation)</option>
<option value="am">Asst. Manager</option>
<option value="dm">Department Manager</option>
<option value="mm"> Mart Manager</option>
<option value="sp">Sales Person</option>
</select><br>
<br><label><b>Gender</b>
<input type="radio" name="gender" value="male" > Male
<input type="radio" name="gender" value="female"> Female<br>
</label>
<p><center>By creating an account you agree to our Terms & Privacy.</center></p>
<div class="clearfix" align="center">
<button type="submit" class="signupbtn" onclick="validation(this.signup_form);"><b>Join Us</b></button>
</div>
</div>
</form>
</body>
</html>
I tried every possible way, but I am not able to resolve the problem.
When you have button type ="submit" in form, your click on submit button will refresh the page.
hence even if your validation function is executed you can not see error or success message.
what you need to do is prevent this default behaviour either with event.preventDefault() in validation method or change type of button to button.
In your case change button type="submit" to type="button".
You had many syntax errors in your code, which caused it to not execute.
You should also use addEventListener instead of an inline onsubmit event handler.
<!DOCTYPE html>
<html><head>
<style>
body {font-family: Arial, Helvetica, sans-serif;
background-color: black;}
* {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: #C0C0C0;
}
input[type=text]:focus, input[type=password]:focus {
background-color: #ffbf00;
outline: none;
}
hr {
border: 1px solid #000000;
margin-bottom: 25px;
}
/* Set a style for all buttons */
button {
background-color: #4CAF50;
color: darkgreen;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 50%;
opacity: 0.9;
}
button:hover {
opacity:1;
}
/* Extra styles for the cancel button */
.cancelbtn {
padding: 14px 20px;
background-color: #f44336;
}
/* Add padding to container elements */
.container {
padding: 16px;
background-color: white;
}
/* Clear floats */
.clearfix::after {
content: "";
clear: both;
display: table;
}
.signupbtn {
width: 50%;
}
</style>
<script type="text/javascript">
function validation() {
alert('in..');
var uname = document.signup_form.username.value;
var mail= document.signup_form.email.value;
var num= document.signup_form.phone.value;
var pass= document.signup_form.psw.value;
var des= document.signup_form.desg.value;
alert('validating...');
if (allLetter(uname)&&ValidateEmail(mail)&&check_phonenumber(num)&&CheckPassword(pass)&&desgselect(des)){
return true;
}
return false;
}
function allLetter(uname){
alert('validating username');
var letters = /^[A-Za-z]+$/;
if(uname.match(letters)) {
alert('corret name');
return true;
}else{
alert('Username must have alphabet characters only');
return false;
}
}
function ValidateEmail(mail){
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(signup_form.email.value)){
alert('valid mail ID');
return (true);
}
alert("You have entered an invalid email address!");
return (false);
}
function check_phonenumber(num){
var phoneno = /^\d{10}$/;
if(num.match(phoneno)){
alert('valid phone number');
return true;
} else{
alert("invalid phone number");
return false;
}
}
function CheckPassword(pass){
var passw= /^[A-Za-z]\w{7,15}$/;
if(pass.match(passw)) {
alert('Correct, try another...');
return true;
}else{
alert('Wrong...!');
return false;
}
}
function desgselect(des){
if(des == "Default"){
alert('Select your designation from the list');
desg.focus();
return false;
}else{
alert('selected correct designation');
return true;
}
}
//}
window.onload = function(){
document.getElementById("signupform").addEventListener("submit", function(e){
validation();
});
}
</script>
</head>
<body>
<form id="signupform" name="signup_form" action="main.html" method="post" style="border:1px solid #ccc">
<div class="container">
<h1><center>Sign Up</center></h1>
<p><center>Please fill in this form to create an account.</center></p>
<hr>
<label for="username"><b>Name</b></label>
<input type="text" placeholder="Enter your full name" name="username" required>
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" required>
<label for="phone"><b>Phone</b></label>
<input type="text" id="phone" name="phone" placeholder="Enter your mobile number" required><br>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<label for="desg"><b>Designation</b></label>
<select name="desg">
<option selected="" value="Default">(Please select your designation)</option>
<option value="am">Asst. Manager</option>
<option value="dm">Department Manager</option>
<option value="mm"> Mart Manager</option>
<option value="sp">Sales Person</option>
</select><br>
<br><label><b>Gender</b>
<input type="radio" name="gender" value="male" > Male
<input type="radio" name="gender" value="female"> Female<br>
</label>
<p><center>By creating an account you agree to our Terms & Privacy.</center></p>
<div class="clearfix" align="center">
<button type="submit" class="signupbtn" onclick="validation(this.signup_form);"><b>Join Us</b></button>
</div>
</div>
</form>
</body>
</html>

JQuery Register Form Validation

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.

Categories