How to add email validation in bootstrap? - javascript

I am using bootstrap in my web page and trying to make a form on that page.
I've used the standard classes of bootstrap for making the form. I've already used the validation to check the emptiness of the form. I just want to add the email and phone number validation further in my code.
The code for the form and the and the already declared validation script is given below:
<script type="text/javascript">
function validateText(id) {
if ($("#" + id).val() == null || $("#" + id).val() == "") {
var div = $("#" + id).closest("div");
div.removeClass("has-success");
$("#glypcn" + id).remove();
div.addClass("has-error has-feedback");
div.append('<span id="glypcn' + id
+ '" class="glyphicon glyphicon-remove form-control-feedback"></span>');
return false;
} else {
var div = $("#" + id).closest("div");
div.removeClass("has-error");
$("#glypcn" + id).remove();
div.addClass("has-success has-feedback");
div.append('<span id="glypcn' + id
+ '" class="glyphicon glyphicon-ok form-control-feedback"></span>');
return true;
}
}
$(document).ready(function() {
$("#contactButton").click(function() {
if (!validateText("contactName")) {
return false;
}
if (!validateText("contactEmail")) {
return false;
}
if (!validateText("contactMobile")) {
return false;
}
if (!validateText("contactAddress1")) {
return false;
}
if (!validateText("contactCity")) {
return false;
}
$("form#contactForm").submit();
}
);
});
<form class="form-horizontal" id="contactForm">
<div class="form-group">
<label for="contactName" class="col-sm-2 control-label">Name<sup>*</sup></label>
<div class="col-sm-10">
<input type="text" class="form-control" id="contactName">
</div>
</div>
<div class="form-group">
<label for="contactEmail" class="col-sm-2 control-label">Email<sup>*</sup></label>
<div class="col-sm-10">
<input type="email" class="form-control" id="contactEmail">
</div>
</div>
<div class="form-group">
<label for="contactMobile" class="col-sm-2 control-label">Mobile
Number<sup>*</sup>
</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="contactMobile">
</div>
</div>
<div class="form-group">
<label for="contactAddress1" class="col-sm-2 control-label">Address1<sup>*</sup></label>
<div class="col-sm-10">
<textarea class="form-control" rows="5" id="contactAddress1"></textarea>
</div>
</div>
<div class="form-group">
<label for="contactAddress2" class="col-sm-2 control-label">Address2</label>
<div class="col-sm-10">
<textarea class="form-control" rows="5" id="contactAddress2"></textarea>
</div>
</div>
<div class="form-group">
<label for="contactCity" class="col-sm-2 control-label">City<sup>*</sup></label>
<div class="col-sm-10">
<select class="form-control" id="contactCity">
<option>KURUKSHETRA</option>
<option>PEHOWA</option>
<option>KARNAL</option>
</select>
</div>
</div>
<div class="col-xs-12 col-lg-12 col-md-12 col-sm-12">
<p>
<span id="helpBlock" class="help-block"><sup>*</sup> marked fields
are compulsory!</span>
</p>
</div>
<div class="checkbox">
<label> <input type="checkbox"> I agree to the <a href="#">Terms of
Service</a>
</label>
</div>
<div class="col-xs-12 col-lg-12 col-md-12 col-sm-12">
<center>
<p>
<button type="button" class="btn btn-primary btn-lg btn-block"
id="contactButton">
Submit <span class="glyphicon glyphicon-arrow-right"> </span>
</button>
</p>
</center>
</div>
</form>

You should use a regex like mentioned in the comment.
The regex is also mentioned here.
var email_regex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i;
Here is a working example.

you have to require additional plugin for this.
Try this:
<form id="emailForm" class="form-horizontal">
<div class="form-group">
<label class="col-xs-3 control-label">Email address</label>
<div class="col-xs-7">
<input type="text" class="form-control" name="email" />
</div>
</div>
</form>
<script>
$(document).ready(function() {
$('#emailForm').formValidation({
framework: 'bootstrap',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
email: {
validators: {
emailAddress: {
message: 'The value is not a valid email address'
}
}
}
}
});
});
</script>

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.

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()
}

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.

Validation of code

I have developed some code in bootstrap and I am getting an error while I was validating the fields (name, email). Please help me out.
This is the code for the form:
<div class="container">
<h3 class="text-center">CONTACT</h3>
<p class="text-center"><em>I love my Fans!</em></p>
<div class="row test">
<div class="col-md-4">
<p><span class="glyphicon glyphicon-map-marker"></span>4429, Rainier Street, Irving, Texas ,United States</p>
<p><span class="glyphicon glyphicon-phone"></span>Phone:Phone</p>
<p><span class="glyphicon glyphicon-envelope"></span>Email: Email</p>
</div>
<div class="col-md-8">
<div class="row">
<div class="col-sm-6 form-group">
<input class="form control" id="name" placeholder="Name" type="text" onBlur="txt_Blur(this,'errorName')" />
<span id="errorName" style="display:none;">Please enter a valid name!</span>
</div>
<div class="col-sm-6 form-group">
<input class="form control" id="email" name="email" placeholder="Email" type="email" required>
<span id="errorName" style="display:none;">Please enter a valid email!</span>
</div>
</div>
<div class="textarea">
<textarea class="form-control" id="comments" name="comments" placeholder="Comment" rows="5"></textarea>
<span id="errorName" style="display:none">Please enter your comments!</span>
</div>
<br>
<div class="row">
<div class="col-md-12 form-group">
<button class="btn pull-right" type="submit" onclick="button_Click()">Send</button>
</div>
</div>
</div>
</div>
</div>
The JavaScript for validation below:
function txt_Blur(ref, errorId) {
if (ref.value == "") {
document.getElementById(errorId).style = "color:red;";
} else {
document.getElementById(errorId).style = "display:none;";
}
}
function button_Click() {
if (document.getElementById("name")).value == "") {
document.getElementById("errorName").style = "color:red;";
} else {
document.getElementById("errorName").style = "display:none;";
}
if (document.getElementById("email")).value == "") {
document.getElementById("errorName").style = "color:red;";
} else {
document.getElementById("errorName").style = "display:none;";
}
}
I need the error displayed when someone tries to leave the name field empty and goes to the next text field (email).

Open modal only when form is validated

I want to open a modal dialog box only when form is completely validated with no error. At first i have disabled my button so that it should validate first and it should be enable only when form is validated. I am using jquery validation for this but does not get the result which i want. I want when user click submit button if fields are not filled it should not open modal.
here is my HTML code
<div class="form-group">
<div class="col-sm-4 col-sm-offset-2">
<button class="btn btn-white" type="reset">Cancel</button>
<!-- Trigger the modal with a button -->
<button type="button" id="myBtn" class="btn btn-primary" data-toggle="modal" data-target="#myModal" disabled />Confirm</button>
</div>
</div>
and me jquery for this
(function() {
$('#PasswordForm > input').keyup(function() {
var empty = false;
$('#PasswordForm > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#myBtn').attr('disabled', 'disabled');
} else {
$('#myBtn').removeAttr('disabled');
}
});})()
The form validation which i used is
$(document).ready(function()
{
$('#PasswordForm').formValidation({
message: 'This value is not valid',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields:
{
NPassword:
{
validators:
{
notEmpty:
{
message: 'The password is required and can\'t be empty'
}
}
},
RPassword:
{
validators:
{
notEmpty:
{
message: 'The confirm password is required and can\'t be empty'
},
identical:
{
field: 'NPassword',
message: 'The password and its confirm are not the same'
}
}
}
}
});
});
<form id="PasswordForm" method="post" class="form-horizontal" action="/HRM/HRM.PasswordChange">
<div class="hr-line-dashed"></div>
<div class="form-group">
<label class="col-sm-2 control-label">Employee Name</label>
<div class="col-sm-10">
<input type="text" disabled="" value="##UserName##" class="form-control">
</div>
</div>
<div class="hr-line-dashed"></div>
<div class="form-group">
<label class="col-sm-2 control-label">New Password</label>
<div class="col-sm-10">
<div class="row">
<div class="col-md-6">
<input type="password" name="NPassword" placeholder="New Password" class="form-control">
</div>
</div>
</div>
</div>
<div class="hr-line-dashed"></div>
<div class="form-group">
<label class="col-sm-2 control-label">Retype Password</label>
<div class="col-sm-10">
<div class="row">
<div class="col-md-6">
<input type="password" name="RPassword" placeholder="Retype Password" class="form-control">
</div>
</div>
</div>
</div>
<div class="hr-line-dashed"></div>
<div class="form-group">
<div class="col-sm-4 col-sm-offset-2">
<button class="btn btn-white" type="reset">Cancel</button>
<!-- Trigger the modal with a button -->
<button type="button" id="myBtn" class="btn btn-primary" data-toggle="modal" data-target="#myModal" disabled />Confirm</button>
</div>
</div>
</form>
any suggestion or help would be appreciated.
Try to change your button to:
<button type="button" id="myBtn" class="btn ban-primary">Confirm</button>
And add following function:
$('#myBtn').on('click', function(){
if(!empty) {
$('#myModal').modal('toggle');
}
});
You have to make empty a global variable.
(untested code)

Categories