Validate form with bootstrap (novalidate) - javascript

I have a problem validating a form with bootstrap novalidate.
Some form fields include the "required" tag and others do not.
To verify, I submit the form with no data and the 'was-validated' class makes all the fields validated, the ones with the "required" tag are marked in red and the others in green.
The idea is to specify which fields to validate instead of the entire form.
Could you help me please?
Form
<form id="Data" method="POST" class="needs-validation mt-0" novalidate>
<div class="row mb-1">
<div class="col-lg-12 ">
<div class="form-group">
<label class="d-block font-weight-semibold">Name: <span class="text-danger">*</span></label>
<input type="text" id="name" name="Name" class="form-control" autocomplete="off" required>
</div>
</div> <!-- / col -->
</div> <!-- / row-->
<div class="row mb-1">
<div class="col-lg-12 ">
<div class="form-group">
<label class="d-block font-weight-semibold">Lastname: <span class="text-danger">*</span></label>
<input type="text" id="lastname" name="lastname" class="form-control" autocomplete="off" required>
</div>
</div> <!-- / col -->
</div> <!-- / row-->
<div class="row mb-1">
<div class="col-lg-12 ">
<div class="form-group">
<label class="d-block font-weight-semibold">Street: <span class="text-danger">*</span></label>
<input type="number" id="Street" name="Street" class="form-control">
</div>
</div> <!-- / col -->
</div> <!-- / row-->
</form>
JS
<script type="text/javascript">
$('#Data').on('submit', function(e){
e.preventDefault();
var form = document.getElementById('Data');
if (!form.checkValidity()) {
e.preventDefault();
e.stopPropagation();
}
else {
$.ajax({
//url: "",
type: $('#Data').attr('method'),
data: $('#Data').serialize(),
//dataType: 'json',
beforeSend: function(){ },
success:function(response) {
if (response.success == true) {
}
else {
}
}
})
}
$('#Data').addClass('was-validated');
});
</script>

Call checkValidity() for each field that need checking, not the complete form:
var formFlag = true;
var nameField = document.getElementById("name");
if (!nameField.checkValidity()) {
nameField.classList.add("is-invalid");
formFlag = false;
}
var lastnameField = document.getElementById("lastname");
if (!lastnameField.checkValidity()) {
lastnameField.classList.add("is-invalid");
formFlag = false;
}
if (!formFlag) {
e.preventDefault();
e.stopPropagation();
return;
} else {

Related

Why is my submit button disabled on the first submit attempt and then enabled on the second attempt

I'm working with Bootstrap Validator and a multi-page modal. I have a form inside a multi-page modal and all the validation rules that I set in the JS code are respected, but something curious happens: no matter how many inputs I fill or if there are no inputs that don't respect the validation rules I set, once I try to send the information, the submit button turns disabled; then I have to clear one of the fields that are considered on the validator and fill it back again so that the submit button turns enabled again and once I press it, it finally submits the information.
Here's my BS Validator code:
$('#modalAgregarEmpleado').bootstrapValidator(
{
fields:
{
r_no_empleado:
{
validators:
{
notEmpty:
{
message: 'Campo requerido'
},
remote:
{
url: '/assets/empleados.php'
}
}
},
correo:
{
validators:
{
emailAddress:
{
message: 'Formato de correo electrónico inválido'
}
}
}
}
})
.on('error.field.bv', function(e,data)
{
if(data.bv.getSubmitButton())
{
data.bv.disableSubmitButtons(false);
}
})
.on('status.field.bv',function(e,data)
{
if(data.bv.getSubmitButton())
{
data.bv.disableSubmitButtons(false);
}
});
My HTML code:
<div class="modal fade" id="modalAgregarEmpleado" role="dialog">
<div class="modal-dialog modal-lg">
<form role="form" method="post" enctype="multipart/form-data">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title"><b>REGISTRO</b></h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<div class="modal-split">
<div class="form-row">
<div class="col-md-2 mb-3">
<label for="employee">EMPLOYEE NUMBER:</label>
<input type="number" name="employee" class="form-control" autocomplete="chrome-off">
</div>
<div class="col-md-4 mb-3">
<label for="name">NAME:</label>
<input type="text" name="name" class="form-control" autocomplete="chrome-off">
</div>
<div class="col-md-3 mb-3">
<label for="lastname">LASTNAME:</label>
<input type="text" name="lastname" class="form-control" autocomplete="chrome-off">
</div>
</div>
<div class="form-row">
<div class="col-md-4 mb-3">
<label for="tel">PHONE NUMBER:</label>
<input type="number" name="tel" class="form-control" autocomplete="chrome-off">
</div>
<div class="col-md-4 mb-3">
<label for="email">E-MAIL:</label>
<input type="email" name="correo" class="form-control" autocomplete="chrome-off">
</div>
</div>
<div class="modal-split">
<div class="form-row">
<div class="col-md-4 mb-3">
<label>DATE:</label>
<input type="text" name="date" id="date" class="form-control" placeholder="aaaa-mm-dd">
</div>
<div class="col-md-4 mb-3">
<label>CLOCK-IN:</label>
<input type="text" name="clockin" id="clockin" class="form-control timepicker" autocomplete="chrome-off">
</div>
<div class="col-md-4 mb-3">
<label>CLOCK-OUT:</label>
<input type="text" name="clockout" id="clockout" class="form-control timepicker" autocomplete="chrome-off">
</div>
</div>
</div>
<div class="modal-footer">
</div>
</div>
</div>
</form>
</div>
</div>
My multi-page modal JS code:
$(document).ready(function()
{
prep_modal();
});
function prep_modal()
{
$(".modal").each(function()
{
var element = this;
var pages = $(this).find('.modal-split');
if (pages.length != 0)
{
pages.hide();
pages.eq(0).show();
var b_button = document.createElement("button");
b_button.setAttribute("type","button");
b_button.setAttribute("class","btn btn-primary");
b_button.setAttribute("style","display: none;");
b_button.innerHTML = "BACK";
var n_button = document.createElement("button");
n_button.setAttribute("type","button");
n_button.setAttribute("class","btn btn-primary");
n_button.innerHTML = "NEXT";
var s_button = document.createElement("button");
s_button.setAttribute("type","submit");
s_button.setAttribute("class","btn btn-primary");
s_button.setAttribute("style","display: none;");
s_button.innerHTML = "SAVE";
$(this).find('.modal-footer').append(b_button).append(n_button).append(s_button);
var page_track = 0;
$(n_button).click(function()
{
this.blur();
if(page_track == 0)
{
$(b_button).show();
}
if(page_track == pages.length-2)
{
$(n_button).hide();
$(s_button).show();
}
if(page_track == pages.length-1)
{
$(element).find("form").submit();
}
if(page_track < pages.length-1)
{
page_track++;
pages.hide();
pages.eq(page_track).show();
}
});
$(b_button).click(function()
{
if(page_track == 1)
{
$(b_button).hide();
}
if(page_track == pages.length-1)
{
$(s_button).hide();
$(n_button).show();
}
if(page_track > 0)
{
page_track--;
pages.hide();
pages.eq(page_track).show();
}
});
}
});
}
The HTML part is a translated and compressed version of the actual code. The original code is in Spanish and more extended.

Radio button validation alert not showing - works on everything else

I'm creating a cfmail form for a nonprofit to allow potential vendors to request a spot at the next fundraiser. All fields are required but the radio buttons are not showing the validation alert if not selected.
EDIT:
I need the user to check either Yes or No when asked "Will vendor be selling at the event?" If the user checks "Yes", we'll display additional fields (State Tax ID and a textarea asking for more details on their product) that will be REQUIRED. If the user selects "NO" the TaxID and Details will NOT be required but we will be eventually be adding questions as to if they're a 501c3 or not.
I'm javascript illiterate so I had someone else write the JS but she had to move on to other obligations before getting the radio buttons working and I need this working before she'll have time to get back to it. Any help would be greatly appreciated.
Here's the Code:
// phone number
function phoneFormat(input) { //returns (###) ###-####
input = input.replace(/\D/g, '');
var size = input.length;
if (size > 0) {
input = "(" + input
}
if (size > 3) {
input = input.slice(0, 4) + ") " + input.slice(4, 11)
}
if (size > 6) {
input = input.slice(0, 9) + "-" + input.slice(9)
}
return input;
}
$(document).ready(function() {
$("#submitall").click(function() {
if (oked) {
$('#submitall').prop('disabled', true);
$("#submitall").html("Sending...");
$("#submitall").submit();
}
});
$('#salesyes').click(function() {
if ($('#salesyes').is(':checked')) {
$("#statesales").css("display", "block");
$("#StateTaxNumber").prop('required', true);
$("#Details").prop('required', true);
} else {
$("#statesales").css("display", "none");
$("#StateTaxNumber").prop('required', false);
$("#Details").prop('required', false);
}
});
$('#salesno').click(function() {
if ($('#salesno').is(':checked')) {
$("#statesales").css("display", "none");
$("#StateTaxNumber").prop('required', false);
$("#Details").prop('required', false);
} else {
$("#statesales").css("display", "block");
$("#StateTaxNumber").prop('required', true);
$("#Details").prop('required', true);
}
});
});
function countChecked() {
//$("#validateSend").bind('change', function() {
console.log("validateSend clicked");
var cBox = $("#validateSend");
console.log(cBox);
console.log(cBox.prop('checked'));
if (cBox.prop('checked')) {
$('#submitall').prop('disabled', false);
} else {
$('#submitall').prop('disabled', true);
}
}; //end countchecked
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false || $('input[name="Sales"]:checked').length == 0) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<!-- vendor app -->
<div class="container mt-2">
<div class="row justify-content-center mt-5">
<div class="col-sm-12 col-md-10 Sponsors text-center">
<form class="needs-validation" action="/Vendors/index.cfm" id="Vendors" method="post" novalidate>
<input type="hidden" name="Vendors_submit" value="yes">
<!-- company name -->
<div class="form-group row">
<label for="Company" class="form-label text-right">Business/Organization:<sup class="text-danger">*</sup></label>
<input id="Company" name="Company" placeholder="Business/Organization Name" type="text" class="form-control" style="text-transform: capitalize;" required>
<div class="valid-feedback">
Looks good!
</div>
<div class="invalid-feedback text-left">
Please enter the name of the company or individual interested in the Vendor spot.
</div>
</div>
<!-- phone -->
<div class="form-group row">
<label for="Phone" class="form-label text-right">Phone:<sup class="text-danger">*</sup></label>
<input id="phone" name="phone" type="tel" placeholder="(555) 555-5555" class="form-control input-md" onInput="this.value = phoneFormat(this.value)" />
<div class="valid-feedback">
Looks good!
</div>
<div class="invalid-feedback text-left">
Please enter your phone number.
</div>
</div>
<!-- is vendor selling? -->
<div class="form-group row mt-5">
<div class="col-12 text-center">
<strong>Will vendor be selling at the event?<sup class="text-danger">*</sup></strong>
</div>
</div>
<div class="form-group row">
<div class="col-12 text-center my-auto">
<input class="align-left" type="radio" name="Sales" id="salesyes" value="Yes" required> Yes
<input class="align-left ml-5" type="radio" name="Sales" id="salesno" value="No"> No
</div>
<div class="valid-feedback">
Looks good!
</div>
<div class="invalid-feedback text-center">
Please select Yes or No.
</div>
</div>
<!-- State Sales Tax certificate -->
<div id="statesales" style="display:none">
<div class="form-group row">
<div class="col-12 text-left font-italic text-danger mb-4">
Some notice stuff here.
</div>
</div>
<div class="form-group row">
<label for="StateTaxNumber" class="form-label text-left">State Sales Tax Number:<sup class="text-danger">*</sup></label>
<input id="StateTaxNumber" name="StateTaxNumber" placeholder="State Sales Tax Number if applicable" type="text" class="form-control">
<div class="valid-feedback">
Looks good!
</div>
<div class="invalid-feedback text-left">
Please enter State sales tax number.
</div>
</div>
<!-- details -->
<div class="form-group row">
<label for="Details" class="form-label">Please describe product or service for sale:<sup class="text-danger">*</sup></label>
<textarea id="Details" name="Details" cols="40" rows="5" class="form-control"></textarea>
<div class="valid-feedback">
Looks good!
</div>
<div class="invalid-feedback text-left">
Please enter your details.
</div>
</div>
</div>
<!--./end display-none -->
<!-- agree to regulations / restrictions -->
<div class="form-group row justify-content-center">
<div class="col-10 text-center my-auto text-danger">
<input type="checkbox" name="validateSend" id="validateSend" value="1" onclick="countChecked();" /><sup class="text-danger">*</sup>
<i>I have read and understand all the Park's rules and regulations as well as the Requirements and Restrictions listed above.<sup class="text-danger">*</sup>
<div class="valid-feedback">
Looks good!
</div>
<div class="invalid-feedback text-left">
Please enter your details.
</div>
</div>
</div>
<div class="form-group row">
<div class="col-12">
<button name="submitall" id="submitall" type="submit" class="btn btn-lg btn-danger mt-4 ml-2 text-center" disabled="disabled">Send Request</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>

How to clear javascript validation error messages with the reset button

I have a simple form page, where there are several form validations. So far, the RESET button only clears the text field values.
But I need the validation messages to clear when the RESET button is pressed.
So far I have seen jQuery methods, but have no idea of implementing it as I am still learning.. Are there any other methods to do this without jQuery..?
Any help would be highly appreciated.
Here's my code...
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="author" content="Koshila">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Contact|Frittery</title>
<link rel="stylesheet" href="about.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/css/bootstrap.min.css" integrity="sha384-VCmXjywReHh4PwowAiWNagnWcLhlEJLA5buUprzK8rxFgeH0kww/aWY76TfkUoSX" crossorigin="anonymous">
<script>
function validation() {
var formFname = document.getElementById("fname").value;
var formLname = document.getElementById("lname").value;
var formEmail = document.getElementById("email").value;
var formNumber = document.getElementById("pnumber").value;
//Validate first name
if (formFname.length == 0) {
document.getElementById("fnameMessage").innerHTML = "<em>You did not enter your first name</em>"
}
//Validate last name
if (formLname.length == 0) {
document.getElementById("lnameMessage").innerHTML = "<em>You did not enter your last name</em>"
}
//Validate email
if (formEmail.length == 0) {
document.getElementById("emailMessage").innerHTML = "<em>You did not enter your email</em>"
} else {
var regex = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (regex.test(formEmail) === false) {
document.getElementById("emailMessage").innerHTML = "<em>Please enter a valid email</em>"
}
}
//Validate phone
if (formNumber.length == 0) {
document.getElementById("phoneMessage").innerHTML = "<em>You did not enter your phone number</em>"
} else if (formNumber.length != 10) {
document.getElementById("phoneMessage").innerHTML = "<em>Phone Number must be exactly 10 digits</em>"
return false;
} else
return true;
}
</script>
</head>
<body>
<div class="container">
<h2>General Enquiry Form</h2>
<form method="POST" action="#" onsubmit="validation(); return false;">
<div class="form-group row">
<label class="col-form-label col-sm-2" for="fname">First Name</label>
<div class="col-sm-6">
<input class="form-control" type="text" id="fname" name="fname">
</div>
<div class="col-sm-4">
<span id="fnameMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="lname">Last Name</label>
<div class="col-sm-6">
<input class="form-control" type="text" id="lname" name="lname">
</div>
<div class="col-sm-4">
<span id="lnameMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="email">Email</label>
<div class="col-sm-6">
<input class="form-control" type="email" id="email" name="email">
</div>
<div class="col-sm-4">
<span id="emailMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="pnumber">Phone</label>
<div class="col-sm-6">
<input class="form-control" type="tel" id="pnumber" name="pnumber">
</div>
<div class="col-sm-4">
<span id="phoneMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="message">Message</label>
<div class="col-sm-10">
<textarea class="form-control" id="message" name="message" style="height: 200px;"></textarea>
</div>
</div>
<div class="form-group row">
<div class="offset-sm-2 ">
<button type="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-secondary">Reset</button>
</div>
</div>
</form>
</div>
<hr>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/js/bootstrap.min.js" integrity="sha384-XEerZL0cuoUbHE4nZReLT7nx9gQrQreJekYhJD9WNWhH8nEW+0c5qq7aIo2Wl30J" crossorigin="anonymous"></script>
</body>
</html>
Don't reset them manual by repeating code. Define a custom reset function which iterates over error messages and empty all of them:
function resetForm() {
var elems = document.querySelectorAll(".text-danger");
elems.forEach(itm => {
document.getElementById(itm.id).innerHTML = ''
})
}
Also don't put any script tag in your head tag. Read more here
Full code:
function resetForm() {
var elems = document.querySelectorAll(".text-danger");
elems.forEach(itm => {
document.getElementById(itm.id).innerHTML = ''
})
}
function validation() {
var formFname = document.getElementById("fname").value;
var formLname = document.getElementById("lname").value;
var formEmail = document.getElementById("email").value;
var formNumber = document.getElementById("pnumber").value;
//Validate first name
if (formFname.length == 0) {
document.getElementById("fnameMessage").innerHTML = "<em>You did not enter your first name</em>"
}
//Validate last name
if (formLname.length == 0) {
document.getElementById("lnameMessage").innerHTML = "<em>You did not enter your last name</em>"
}
//Validate email
if (formEmail.length == 0) {
document.getElementById("emailMessage").innerHTML = "<em>You did not enter your email</em>"
} else {
var regex = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (regex.test(formEmail) === false) {
document.getElementById("emailMessage").innerHTML = "<em>Please enter a valid email</em>"
}
}
//Validate phone
if (formNumber.length == 0) {
document.getElementById("phoneMessage").innerHTML = "<em>You did not enter your phone number</em>"
} else if (formNumber.length != 10) {
document.getElementById("phoneMessage").innerHTML = "<em>Phone Number must be exactly 10 digits</em>"
return false;
} else
return true;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="author" content="Koshila">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Contact|Frittery</title>
<link rel="stylesheet" href="about.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/css/bootstrap.min.css" integrity="sha384-VCmXjywReHh4PwowAiWNagnWcLhlEJLA5buUprzK8rxFgeH0kww/aWY76TfkUoSX" crossorigin="anonymous">
</head>
<body>
<div class="container">
<h2>General Enquiry Form</h2>
<form method="POST" action="#">
<div class="form-group row">
<label class="col-form-label col-sm-2" for="fname">First Name</label>
<div class="col-sm-6">
<input class="form-control" type="text" id="fname" name="fname">
</div>
<div class="col-sm-4">
<span id="fnameMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="lname">Last Name</label>
<div class="col-sm-6">
<input class="form-control" type="text" id="lname" name="lname">
</div>
<div class="col-sm-4">
<span id="lnameMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="email">Email</label>
<div class="col-sm-6">
<input class="form-control" type="email" id="email" name="email">
</div>
<div class="col-sm-4">
<span id="emailMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="pnumber">Phone</label>
<div class="col-sm-6">
<input class="form-control" type="tel" id="pnumber" name="pnumber">
</div>
<div class="col-sm-4">
<span id="phoneMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="message">Message</label>
<div class="col-sm-10">
<textarea class="form-control" id="message" name="message" style="height: 200px;"></textarea>
</div>
</div>
<div class="form-group row">
<div class="offset-sm-2 ">
<button onclick="validation(); return false;" class="btn btn-primary">Submit</button>
<button class="btn btn-secondary" onclick="resetForm(); return false;">Reset</button>
</div>
</div>
</form>
</div>
<hr>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/js/bootstrap.min.js" integrity="sha384-XEerZL0cuoUbHE4nZReLT7nx9gQrQreJekYhJD9WNWhH8nEW+0c5qq7aIo2Wl30J" crossorigin="anonymous"></script>
</body>
<button type="reset" class="btn btn-secondary" onclick="clearErrors();">Reset</button>
function clearErrors() {
document.getElementById("emailMessage").innerHTML = "";
// ... repeat for other messages
}
You need to call the eraseText function separately like mentioned below
function eraseText() {
document.getElementById("fnameMessage").innerHTML = "";
document.getElementById("lnameMessage").innerHTML = "";
document.getElementById("emailMessage").innerHTML = "";
document.getElementById("phoneMessage").innerHTML = "";
}
<button onClick="eraseText()" type="reset" class="btn btn- secondary">Reset</button>
As the error/validation messages are displayed within span elements of the same class text-danger you can easily query the DOM using querySelectorAll to return a nodelist and then iterate through that collection and set the span text content to an empty string.
Note that I added a name to the form and used that name within the anonymous function in the event handler. With a name assigned to the form also means that you can identify elements simply by doing something like this:
const form=document.forms.enquiry;
const formFname=form.fname;
const formLname=form.lname;
etc etc
document.querySelector('button[type="reset"]').addEventListener('click',e=>{
e.preventDefault();
document.querySelectorAll('.text-danger').forEach(span=>span.textContent='')
document.forms.enquiry.reset()
})
function validation()
{
var formFname = document.getElementById("fname").value;
var formLname = document.getElementById("lname").value;
var formEmail = document.getElementById("email").value;
var formNumber = document.getElementById("pnumber").value;
//Validate first name
if(formFname.length ==0)
{
document.getElementById("fnameMessage").innerHTML ="<em>You did not enter your first name</em>"
}
//Validate last name
if(formLname.length ==0)
{
document.getElementById("lnameMessage").innerHTML ="<em>You did not enter your last name</em>"
}
//Validate email
if(formEmail.length ==0)
{
document.getElementById("emailMessage").innerHTML ="<em>You did not enter your email</em>"
}
else
{
var regex = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(regex.test(formEmail)===false)
{
document.getElementById("emailMessage").innerHTML ="<em>Please enter a valid email</em>"
}
}
//Validate phone
if(formNumber.length ==0)
{
document.getElementById("phoneMessage").innerHTML ="<em>You did not enter your phone number</em>"
}
else if(formNumber.length !=10)
{
document.getElementById("phoneMessage").innerHTML ="<em>Phone Number must be exactly 10 digits</em>"
return false;
}
else
return true;
}
<div class="container">
<h2>General Enquiry Form</h2>
<form name='enquiry' method="POST" action="#" onsubmit="validation(); return false;">
<div class="form-group row">
<label class="col-form-label col-sm-2" for="fname">First Name</label>
<div class="col-sm-6">
<input class="form-control" type="text" id="fname" name="fname" >
</div>
<div class="col-sm-4">
<span id="fnameMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="lname">Last Name</label>
<div class="col-sm-6">
<input class="form-control" type="text" id="lname" name="lname" >
</div>
<div class="col-sm-4">
<span id="lnameMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="email">Email</label>
<div class="col-sm-6">
<input class="form-control" type="email" id="email" name="email" >
</div>
<div class="col-sm-4">
<span id="emailMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="pnumber">Phone</label>
<div class="col-sm-6">
<input class="form-control" type="tel" id="pnumber" name="pnumber">
</div>
<div class="col-sm-4">
<span id="phoneMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="message">Message</label>
<div class="col-sm-10">
<textarea class="form-control" id="message" name="message" style="height: 200px;"></textarea>
</div>
</div>
<div class="form-group row">
<div class="offset-sm-2 ">
<button type="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-secondary">Reset</button>
</div>
</div>
</form>
</div>
take a look for my code
html code:
<div class="tech-news__search__container">
<div class="tech-news__search">
<input
id="subscribeInput"
type="text"
class="tech-news__search-input"
placeholder="example#gmail.com"
>
<button class="tech-news__search-button" id="subscribeButton">Subscribe</button>
</div>
<div class="resultBlock">
<p class="listOfSubscribers" id="listOfSubscribers"></p>
<div id="result"></div>
<div id="deleteAll"></div>
</div>
</div>
js code:
let node = null
let deleteAll
function renderItems() {
const items = getItem()
if (items.length) {
const listOfSubscribers = document.getElementById('listOfSubscribers')
listOfSubscribers.innerHTML = 'Subscribers'
items.map(item => {
node = document.createElement("LI");
let textnode = document.createTextNode(item);
node.appendChild(textnode);
document.getElementById("result").appendChild(node);
})
deleteAll = document.getElementById('deleteAll')
deleteAll.innerHTML = 'Delete All'
deleteAll.addEventListener('click', deleteItems)
}
}
renderItems()
function deleteItems() {
sessionStorage.removeItem('subscribers')
window.location.reload()
}

Check if has class not working

very silly problem but cant seem to get it. i have submit button on form disabled by default. and want to enable if none of the inputs have materialize class invalid or they are empty, works with empty but cant figure out why the check for invalid not working $(this).is( ".invalid" ) code below:
$(document).ready(function() {
$('input').keyup(function() {
var empty = false;
$('input').each(function() {
if (($(this).val().length == 0) || $(this).is( ".invalid" )) {
empty = true;
}
});
var submitBtn = $('.btn[type="submit"]');
if (empty) {
submitBtn.attr('disabled', 'disabled');
} else {
submitBtn.attr('disabled', false);
}
});
});
<div class="container">
<div class="row">
<div class="col s12 ">
<div id="main" class="card">
<div class="card-content deep-orange lighten-5">
<span class="card-title">Ajax Form</span>
<form action="submit">
<div class="row">
<div class="input-field col s6">
<input id="first_name" type="text" class="validate">
<label for="first_name">First Name</label>
</div>
<div class="input-field col s6">
<input id="last_name" type="text" class="validate">
<label for="last_name">Last Name</label>
</div>
</div>
<div class="row">
<div class="input-field col s6">
<input id="email" type="email" class="validate">
<label for="email">Email</label>
</div>
<div class="input-field col s6">
<input id="phone" type="text" class="validate">
<label for="phone">Input</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="age_input" type="number" class="validate">
<label for="age_input">Age</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="noyp_input" type="number" class="validate">
<label for="noyp_input">Number</label>
</div>
</div>
<button class="btn waves-effect waves-light" type="submit" name="action" disabled="disabled">Submit
<i class="material-icons right">send</i>
</button>
</form>
</div>
</div>
</div>
</div>
</div>
I have three suggestions to make and a warning to give regarding your code:
Prefer prop to attr (see this answer).
Break the loop once the flag has been set to true; there is no need to search anymore.
Simply pass the result of the empty flag to the disabled property.
Beware that the content of an input can change via copy-paste, drag-n-drop or through the console and keyboard events such as keyup don't detect such changes.
Code:
/* ----- JavaScript ----- */
$(document).ready(function() {
$('input').keyup(function() {
/* Create a flag. */
var empty = false;
/* If any input is empty or invalid set the flag to true and break. */
$('input').each(function() {
if (!this.value.length || $(this).is(".invalid")) {
empty = true;
return false;
}
});
/* Set 'disabled' to the value of the flag. */
$('.btn[type="submit"]').prop("disabled", empty);
});
});
/* For the other buttons. */
$("#add").click(()=>$('input').addClass("invalid"));
$("#remove").click(()=>$('input').removeClass("invalid"));
<!----- HTML ----->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text"/>
<input type="text"/>
<input type="text"/>
</div>
<div>
<button id = "add">Add 'invalid'</button>
<button id = "remove">Remove 'invalid'</button>
<button class="btn" type="submit" disabled>Submit</button>
</div>
Better use input event instead of keyup as user can paste the value.
Uncomment input class="invalid" in the snippet to test that case.
$(function() {
$('input').on('input', function() {
$('.btn[type="submit"]').prop('disabled',
$.grep($('input'), function(i) {
return i.value === '' || $(i).hasClass('invalid')
}).length > 0)
});
$('form').on('submit', function(e) {
e.preventDefault;
alert('submit')
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input><br>
<input><br>
<!-- input class="invalid"><br -->
<input><br>
<button class="btn" type="submit" disabled>GO</button>
</form>

Form validation with multiple highlighted fields

I have a registration form that I would like to have multiple field validation. What I mean by this is if more than one field is not filled in it will be highlighted red. I have some code already written but instead of highlighting the field not filled in, it's highlighting all of them. I realise it is quite long winded but I'm fairly new to this. My JS code is as follows:
`function formCheck() {
var val = document.getElementById("fillMeIn").value;
var val = document.getElementById("fillMeIn2").value;
var val = document.getElementById("fillMeIn3").value;
var val = document.getElementById("fillMeIn4").value;
var val = document.getElementById("fillMeIn5").value;
var val = document.getElementById("fillMeIn6").value;
var val = document.getElementById("fillMeIn7").value;
if (val == "") {
alert("Please fill in the missing fields");
document.getElementById("fillMeIn").style.borderColor = "red";
document.getElementById("fillMeIn2").style.borderColor = "red";
document.getElementById("fillMeIn3").style.borderColor = "red";
document.getElementById("fillMeIn4").style.borderColor = "red";
document.getElementById("fillMeIn5").style.borderColor = "red";
document.getElementById("fillMeIn6").style.borderColor = "red";
document.getElementById("fillMeIn7").style.borderColor = "red";
return false;
}
else {
document.getElementById("fillMeIn").style.borderColor = "green";
document.getElementById("fillMeIn2").style.borderColor = "green";
document.getElementById("fillMeIn3").style.borderColor = "green";
document.getElementById("fillMeIn4").style.borderColor = "green";
document.getElementById("fillMeIn5").style.borderColor = "green";
document.getElementById("fillMeIn6").style.borderColor = "green";
document.getElementById("fillMeIn7").style.borderColor = "green";
}
}`
My HTML is as follows:
'<form id="mbrForm" onsubmit="return formCheck();" action="thanks.html" method="post">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4 vertical-gap">
FIRST NAME:
<input id="fillMeIn" type="text" class="form-control" placeholder="First Name" >
</div>
<div class="col-md-4 vertical-gap">
LAST NAME:
<input id="fillMeIn2" type="text" class="form-control" placeholder="Last Name" >
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8 vertical-gap">
ADDRESS:
<input id="fillMeIn3" type="text" class="form-control vertical-gap" placeholder="First Line" >
<input id="fillMeIn4" type="text" class="form-control vertical-gap" placeholder="Second Line" >
<input id="fillMeIn5" type="text" class="form-control vertical-gap" placeholder="Town/City" >
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4 vertical-gap">
POST CODE:
<input id="fillMeIn6" type="text" class="form-control vertical-gap" placeholder="Postcode" >
</div>
<div class="col-md-4 vertical-gap">
PHONE No:
<input type="number" class="form-control vertical-gap" placeholder="Tel no">
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
EMAIL ADDRESS:
<input id="fillMeIn7" type="email" class="form-control vertical-gap" placeholder="Email address" >
</div>
<div class="col-md-2"></div>
</div>
<div class="row vertical-gap">
<div class="col-md-2"></div>
<div class="col-md-8">
DISCIPLINE:
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Cross Country"> CROSS COUNTRY
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Enduro"> ENDURO
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Downhill"> DOWNHILL
</label>
</div>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-10">
<!--<button type="button" input type="hidden" class="btn btn-success" name="redirect" value="thanks.html">SUBMIT</button>-->
<input type="submit" value="SUBMIT" class="btn btn-success btn-lg">
</div>
<div class="col-md-2"></div>
</div>
</form>'
Thanks!
You could have the ids in an Array, iterate through its values, and execute the repeatable code in a function that groups all the logic inside.
example :
["fillMeIn1", "fillMeIn2", "fillMeIn3", "fillMeIn4"].each(function(id){
// do things with id
})
Why not use the html "required" property instead?
If you want to do this with JS, you should give each variable a different name. In the code you posted you are continuously overwriting the same variable, and then, it evaluates val (which ended up being assigned to the (fill me7 value) to "", and if true, setting all the borders to red.
Set different variables, push the input values into an array when submit is triggered and loop through them if variables[i]==0, set getElementId(switch case[i] or another array with the name of the inputs[i]).bordercolor to red.
AGAIN, this sound VERY INEFFICIENT and I am not sure at all it would work. My guess is that it would take A LOT of time, and probably get timed out (except you are using some asych/try-catch kind of JS).
I would simply go for an HTML required property and then override the "required" property in CSS to make it look as you intend to. Simpler, easy and clean.
The main issue in your code is that you override the variable val each time you wrote var val = ....
Keeping your own your logic, you could write something like that.
var formModule = (function () {
var $fields = [
document.getElementById('fillMeIn'),
document.getElementById('fillMeIn2'),
document.getElementById('fillMeIn3'),
document.getElementById('fillMeIn4'),
document.getElementById('fillMeIn5'),
document.getElementById('fillMeIn6'),
document.getElementById('fillMeIn7')
];
function markInvalid($field) {
$field.style.borderColor = 'red';
}
function markValid($field) {
$field.style.borderColor = 'green';
}
return {
check: function () {
var isValid = true;
$fields.forEach(function ($f) {
if ($f.value === '') {
if (isValid) alert('Please fill in the missing fields');
isValid = false;
markInvalid($f);
}
else markValid($f);
});
return isValid;
}
};
})();
There are some extra concepts in this example which may be useful:
Working with the DOM is really slow, that's why you should
put your elements in a variable once for all and not everytime you
click on the submit button.
In my example i wrap the code with var formModule = (function () {...})();.
It's called module pattern. The goal is to prevent variables to leak in the rest of the application.
A better solution could be this one using the 'power' of html form validation:
HTML:
<form id="mbrForm" action="thanks.html" method="post">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4 vertical-gap">
FIRST NAME:
<input id="fillMeIn" type="text" required class="form-control" placeholder="First Name">
</div>
<div class="col-md-4 vertical-gap">
LAST NAME:
<input id="fillMeIn2" type="text" required class="form-control" placeholder="Last Name">
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8 vertical-gap">
ADDRESS:
<input id="fillMeIn3" type="text" required class="form-control vertical-gap" placeholder="First Line">
<input id="fillMeIn4" type="text" required class="form-control vertical-gap" placeholder="Second Line">
<input id="fillMeIn5" type="text" required class="form-control vertical-gap" placeholder="Town/City">
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4 vertical-gap">
POST CODE:
<input id="fillMeIn6" type="text" required class="form-control vertical-gap" placeholder="Postcode">
</div>
<div class="col-md-4 vertical-gap">
PHONE No:
<input type="number" class="form-control vertical-gap" placeholder="Tel no">
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
EMAIL ADDRESS:
<input id="fillMeIn7" type="email" required class="form-control vertical-gap" placeholder="Email address">
</div>
<div class="col-md-2"></div>
</div>
<div class="row vertical-gap">
<div class="col-md-2"></div>
<div class="col-md-8">
DISCIPLINE:
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Cross Country"> CROSS COUNTRY
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Enduro"> ENDURO
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Downhill"> DOWNHILL
</label>
</div>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-10">
<input id="btnSubmit" type="submit" value="SUBMIT" class="btn btn-success btn-lg">
</div>
<div class="col-md-2"></div>
</div>
</form>
JS:
var formModule = (function () {
var $form = document.getElementById('mbrForm');
var $btn = document.getElementById('btnSubmit');
var $fields = [
document.getElementById('fillMeIn'),
document.getElementById('fillMeIn2'),
document.getElementById('fillMeIn3'),
document.getElementById('fillMeIn4'),
document.getElementById('fillMeIn5'),
document.getElementById('fillMeIn6'),
document.getElementById('fillMeIn7')
];
checkValidation();
$form.addEventListener('change', checkValidation);
$form.addEventListener('keyup', checkValidation);
$fields.forEach(function ($f) {
$f.addEventListener('change', function () {
markInput($f, $f.checkValidity());
});
});
function checkValidation() {
$btn.disabled = !$form.checkValidity();
}
function markInput($field, isValid) {
$field.style.borderColor = isValid ? 'green' : 'red';
}
})();
In this example, the button gets disabled until the form is valid and inputs are validated whenever they are changed.
I added required attribute in HTML inputs so they can be handled by native javascript function checkValidity(). Note that in this case inputs email and number are also correctly checked. You could also use attribute pattern to get a more powerfull validation:
<input type="text" pattern="-?[0-9]*(\.[0-9]+)?">
Hope it helps.

Categories