Bootstrap 4 Form Validation - javascript

I'm a beginner with bootstrap and I have seen a lot of bootstrap 3 form validation plugins etc, but I haven't found any for bootstrap 4.
I'm trying to validate multiple forms, and here is my code:
<!-- Contact -->
<div class="container white">
<div class="row">
<div class="container white percent100">
<div class="col-lg-12">
<div class="padder-t2">
<h1>Contact</h1>
<div class="horiz-divider"></div>
</div>
</div>
</div>
</div>
<div class="row padder-t padder-b">
<div class="container white">
<div class="col-lg-12">
<!-- Form -->
<form class="form-horizontal" action=" " method="post" id="contact_form">
<fieldset>
<!-- Text input-->
<div class="form-group">
<div class="row">
<div class="col-md-4 col-lg-4">
<label class="control-label pull-right"><h4>First Name</h4></label>
</div>
<div class="col-md-4 col-lg-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-user"></i></span>
<input id="firstname" name="firstname" placeholder="First Name" class="form-control" type="text">
</div>
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<div class="row">
<div class="col-md-4 col-lg-4">
<label class="control-label pull-right"><h4>Last Name</h4></label>
</div>
<div class="col-md-4 col-lg-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-user"></i></span>
<input id="lastname" name="lastname" placeholder="Last Name" class="form-control" type="text">
</div>
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<div class="row">
<div class="col-md-4 col-lg-4">
<label class="control-label pull-right"><h4>E-Mail</h4></label>
</div>
<div class="col-md-4 col-lg-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope"></i></span>
<input id="email" name="email" placeholder="E-Mail Address" class="form-control" type="email">
</div>
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<div class="row">
<div class="col-md-4 col-lg-4">
<label class="control-label pull-right"><h4>Phone #</h4></label>
</div>
<div class="col-md-4 col-lg-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-phone"></i></span>
<input id="phone" name="phone" placeholder="Phone" class="form-control" type="text">
</div>
</div>
</div>
</div>
<!-- Text area -->
<div class="form-group">
<div class="row">
<div class="col-md-4 col-lg-4">
<label class="control-label pull-right"><h4>Message</h4></label>
</div>
<div class="col-md-4 col-lg-5 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-pencil"></i></span>
<textarea id="comment" class="form-control" name="comment" placeholder="Your Message"></textarea>
</div>
</div>
</div>
</div>
<!-- Success message -->
<div class="alert alert-success" role="alert" id="success_message">Success <i class="fa fa-thumbs-up"></i> Thanks for contacting us, we will get back to you shortly.</div>
<!-- Button -->
<div class="form-group">
<div class="row">
<label class="col-md-4 col-lg-4 control-label"></label>
<div class="col-md-4 col-lg-4">
<button type="submit" class="btn btn-danger raised">Send <i class="fa fa-paper-plane"></i></button>
</div>
</div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
<div class="row padder-b">
<div class="row col-lg-12">
<div class="col-md-3 col-lg-3"></div>
<h4 class="col-md-9 col-lg-9">Contact us directly:</h4>
</div>
<div class="row col-lg-12">
<div class="col-md-3 col-lg-3"></div>
<h4 class="col-md-2 col-lg-2 padder-lr">Mail:</h4>
<a class="col-md-6 col-lg-6 padder-lr" href="mailto:lorem#ipsum.com">
<h4 id="mail">lorem#ipsum.com</h4>
</a>
</div>
<div class="row col-lg-12">
<div class="col-md-3 col-lg-3"></div>
<h4 class="col-md-2 col-lg-2 padder-lr">Adress:</h4>
<h4 class="col-md-6 col-lg-6 padder-lr" id="adress">2 LoremIpsum Road, 67000 City - Country</h4>
</div>
</div>
</div>
I have tried to modify existing js, but I had no luck.
Here is the rendered form:
jsfiddle of the form

First I solved my issue with an external library like Jonathan Dion suggested. But recently I came across this :
Bootstrap v4.0 introduced their own form validation that you can still pair with backend php validation. From the Doc :
<form class="needs-validation" novalidate>
<div class="form-row">
<div class="col-md-4 mb-3">
<label for="validationCustom01">First name</label>
<input type="text" class="form-control" id="validationCustom01" placeholder="First name" value="Mark" required>
<div class="valid-feedback">
Looks good!
</div>
<div class="invalid-feedback">
Doesn't look good!
</div>
</div>
</div>
</div>
Then using JS :
<script>
// 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) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
</script>
This provides input border colorating and displays the valid / invalid feedback blocks according to the given pattern or properties. It is applied via CSS’s two pseudo-classes, :invalid and :valid. It applies to <input>, <select>, and <textarea> elements.

Update 2020 - Bootstrap 4.4.x
Here's another option (modern JS) if you want to validate each input one at a time (live or real-time) instead of waiting for the entire form to be submitted...
(function() {
'use strict';
window.addEventListener('load', function() {
// fetch all the forms we want to apply custom style
var inputs = document.getElementsByClassName('form-control')
// loop over each input and watch blur event
var validation = Array.prototype.filter.call(inputs, function(input) {
input.addEventListener('blur', function(event) {
// reset
input.classList.remove('is-invalid')
input.classList.remove('is-valid')
if (input.checkValidity() === false) {
input.classList.add('is-invalid')
}
else {
input.classList.add('is-valid')
}
}, false);
});
}, false);
})()
<form class="container" novalidate="" action="/echo" method="POST" id="myForm">
<div class="form-group">
<label class="form-control-label" for="input1">Enter some input</label>
<input type="text" class="form-control" name="input1" id="input1"
autocomplete="no" required>
<div class="valid-feedback">Success! You've done it.</div>
<div class="invalid-feedback">No, you missed this one.</div>
</div>
<div class="form-group">
<label class="form-control-label" for="input2">Enter password</label>
<input type="text" class="form-control"
pattern="^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}$"
autocomplete="no" name="input2" id="input2">
<div class="valid-feedback">Nice! You got this one!</div>
<div class="invalid-feedback">At least 6 chars: 1 uppercase, 1 lowercase and numeric</div>
</div>
<div>
<button type="submit" class="btn btn-secondary" id="btnSubmit">Submit</button>
</div>
</form>
https://codeply.com/p/mzBNbAlOvQ

You can use any library available on the web. You may try jqueryvalidation. It's pretty easy to use, just read the documentation.
Add the required attribute on your input and jqueryvalidation will do the job. For styling, you can add your own CSS and make it look like bootstrap.
Hopes it help
$(document).ready(function(){
$('#contact_form').validate()
})
Demo

I found a simpler and a bit more modern way to implement Bootstrap 4 JS Form validation:
Note: Keep in mind that each <form> element must have the novalidate attribute and at the same time, each <input> element in it must have the required attribute.
// Upon load..
window.addEventListener('load', () => {
// Grab all the forms
var forms = document.getElementsByClassName('needs-validation');
// Iterate over each one
for (let form of forms) {
// Add a 'submit' event listener on each one
form.addEventListener('submit', (evt) => {
// check if the form input elements have the 'required' attribute
if (!form.checkValidity()) {
evt.preventDefault();
evt.stopPropagation();
console.log('Bootstrap will handle incomplete form fields');
} else {
// Since form is now valid, prevent default behavior..
evt.preventDefault();
console.info('All form fields are now valid...');
}
form.classList.add('was-validated');
});
}
});
<!-- Load necessary libraries -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<!-- Add form -->
<div class="container" style="padding-top: 40px;">
<form class="student-search needs-validation" novalidate>
<div class="form-row">
<div class="form-group col-6">
<label for="input-name-search" class="sr-only">Name</label>
<input type="text" class="form-control" id="input-name-search" placeholder="Name" required>
<div class="valid-feedback">Looks good!</div>
<div class="invalid-feedback">Enter a name please.</div>
</div>
<div class="col-6">
<button id="btn-search" type="submit" class="btn btn-success btn-block">Search student</button>
</div>
</div>
</form>
</div>

I just figured out the reason my code wasn't validating: I didn't have a submit button to trigger the validation. Make sure to have it.
<button type="submit" class="btn btn-primary">Save</button>

There's no real need for a library here, you can use the native reportValidation() method: MDN. You can call it on individual inputs or on the entire form itself.

Related

how to display form with div correctly?

I have this part of form field
When user click on the Add button will copy the above form field and user can add more in this field .
but when I add <div id="ownership"> above the code form it start to look like this
I need to put id=ownership because I want to use it in my jQuery function
<div id="ownership">
<div class="col-lg-12 mb-30 ">
<label for="add_owner"><b><span style="color:#e60000;">*</span> Name</b></label><br>
<input class="from-control" type="text" id="name" >
</div>
<div class="col-lg-6 mb-30" >
<label for="add_owner"><b><span style="color:#e60000;">*</span> Phone number</b></label><br>
<div class="input-group-prepend">
<input class="from-control" type="text" id="phone" >
</div>
</div>
<div class="col-lg-6 mb-30" >
<label for="add_owner"><b><span style="color:#e60000;">*</span> Emailn</b></label><br>
<div class="input-group-prepend">
<input class="from-control" type="email" id="email">
</div>
</div>
</div>
<div id="owner"></div>
<br>
<div class="col-md-12">
<button type="button" class="btn btn-success w-30 add_info f-r">Add</button>
</div>
<script>
$(document).ready(function(){
$(".add_info").click(function(){
var newForm = $("#ownership").clone();
$('input', newForm).val('');
$('owner').append(newForm);
});
});
</script>
How do I fix the code in order to achieve the image in number 1 ?
try this
<div class="row">
<div class="col-sm-6"> Text</div>
<div class="col-sm-6"> Text</div>
</div>
you need to apply this format then design will be properly according your desirable.
Try this way. Always use bootstrap col class inside row class then it will not cause unexpected result.
<div class="row">
<div class="col-md-12"></div>
<div class="col-md-6"></div>
<div class="col-md-6"></div>
</div>

Conditional unobtrusive validation

I have 5 or so fields that will be hidden or shown based on the value of a drop down list; however, if they are visible, I need them to be required.
Is there a way to dynamically turn on/off unobtrusive validation for these fields?
Here is some code:
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="col-md-4 control-label">Routing Number</label>
<div class="col-md-8">
<input id="RoutingNumber" asp-for="org.RoutingNumber" class="form-control " autocomplete="off" />
<span asp-validation-for="org.RoutingNumber" class="text-danger"></span>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="col-md-3 control-label">Account Holder Name</label>
<div class="col-md-9">
<input id="AccountHolderName" asp-for="org.AccountHolderName" class="form-control " autocomplete="off" />
<span asp-validation-for="org.AccountHolderName" class="text-danger"></span>
</div>
</div>
</div>
</div>
I would need these fields to be required, ONLY IF a separate drop down list had a certain value

Form validation is not working in MEAN Stack using angular js and node js

Hello I am working with MEAN Stack application.When I add record data stored
Successfully. But When I don't fill any field and click add button which is
Calling function for store record My function working properly But I used the
Validation field is required but function working and redirect my given path.
new data is not storing but why function is working.
function in controller
$scope.adduser = function()
{
$http({
method:"POST",
url:'api/adduser',
data:{name:$scope.name, email:$scope.email,password:$scope.password}
}).then(function successCallback(response) {
if(response.data.error){
$scope.error = response.data.error;
}else{
$scope.Blog=response.data;
$localStorage.dd=$scope.Blog;
$location.path('/allusers');
}
//console.log(response);
}, function errorCallback(response) {
alert("data is not comming here");
});
}
message show field is required but not stay there go to the given path when
response success. how to resolved this problem
view file is
<!-- BEGIN PAGE HEADER-->
<h3 class="page-title">
Advanced Datatables <small>advanced datatable samples</small>
</h3>
<div class="page-bar">
<ul class="page-breadcrumb">
<li>
<i class="fa fa-home"></i>
Home
<i class="fa fa-angle-right"></i>
</li>
<li>
All Users
</li>
</ul>
</div>
<div class="row">
<div class="col-md-12">
<!-- BEGIN VALIDATION STATES-->
<div class="portlet box blue-hoki">
<div class="portlet-title">
<div class="caption">
<i class="fa fa-gift"></i>
New User
</div>
</div>
<div class="portlet-body form">
<form id = "expensesCreate" class="form-horizontal">
<div class="form-body">
<div class="alert alert-danger display-hide">
<button class="close" data-close="alert"></button>
You have some form errors. Please check below.
</div>
</div>
<div class="form-group">
<label for="price" class="col-sm-3">Name</label>
<div class="col-sm-4 #if($errors->has('price')) has-error #endif">
<input class="form-control input-sm" placeholder="" autocomplete="off" id="first_name" name="name" ng-model="name" type="text" value ="" required>
<p class="error"></p>
</div>
</div>
<div class="form-group">
<label for="price" class="col-sm-3">Email</label>
<div class="col-sm-4 #if($errors->has('price')) has-error #endif">
<input class="form-control input-sm" placeholder="" autocomplete="off" id="email" name="email" ng-model="email" type="text" value ="" required>
<p class="error"></p>
</div>
</div>
<div class="form-group">
<label for="Phone_no" class="col-sm-3">Password</label>
<div class="col-sm-4 #if($errors->has('Phone_no')) has-error #endif">
<input class="form-control input-sm" placeholder="" autocomplete="off" id="phone_no" name="company_name" ng-model="password" type="text" value ="" required>
<p class="error"></p>
</div>
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<button ng-click="adduser()" class="btn blue-hoki">Add</button>
<a ng-href="#/allusers">
<button type="button" class="btn default" id="cancel">Cancel</button>
</a>
</div>
</div>
</div>
</div>
</form>
<!-- END FORM-->
</div>
</div>
<!-- END VALIDATION STATES-->
</div>
</div>
<style>
.form-horizontal .form-group {
margin-right: -15px;
margin-left: 0px;
}
</style>
Add disabled attribute on your button validation while the form is invalid
<button ng-click="adduser()" class="btn blue-hoki" ng-disabled="expensesCreate.$invalid">Add</button>

How do I clear or reset data in a form in angularjs?

Been finding how to clear form data with the use of angular and $setPristine Function but still no results always gives me an error saying $setPristine is not a function. Can anyone kindly help me for a solution?
here's my angular.controller
$scope.AddCustomer = function () {
var CustDetails = {
cname: $scope.CusDetails.cname,
comname: $scope.CusDetails.comname,
tel: $scope.CusDetails.tel,
email: $scope.CusDetails.email
};
CustService.Customer(CustDetails, function (res) {
console.log(res);
$.extend($.gritter.options, {
position: 'bottom-right',
});
if (res.data == 'success') {
$.gritter.add({
title: 'Success!',
text: 'Successfully added the new customer ' + '<h4><span class="label label-primary">' + CustDetails.cname + '</span></h4>',
time: '5000',
close_icon: 'l-arrows-remove s16',
icon: 'glyphicon glyphicon-ok-circle',
class_name: 'success-notice'
});
//CustDetails = {};
customerForm.$setPristine(true);
}
else {
$.gritter.add({
title: 'Failed!',
text: 'Failed to add a new customer',
time: '5000',
close_icon: 'l-arrows-remove s16',
icon: 'glyphicon glyphicon-remove-circle',
class_name: 'error-notice'
});
}
});
}
Here's the Html code
<div ng-controller="AddCustomerController">
<div class="page-content-wrapper">
<div class="page-content-inner">
<div id="page-header" class="clearfix">
<div class="page-header">
<h2>Add Customer</h2>
<span class="txt">Create and add new customer.</span>
</div>
</div>
<!--Start .row-->
<div class="row">
<div class="col-md-1">
</div>
<div class="col-lg-9 col-sm-9 col-xs-12">
<!--col-lg-9 starts here-->
<div class="panel panel-default toggle panelMove panelClose panelRefresh">
<div class="panel-heading">
<h4 class="panel-title">Customer Details</h4>
</div>
<div class="panel-body pt0 pb0">
<form class="form-horizontal group-border stripped" id="customerForm">
<div class="form-group">
<label class="col-lg-2 col-md-3 control-label">Customer Name</label>
<div class="col-lg-10 col-md-9">
<input type="text" required id="cname" ng-model="CusDetails.cname" class="form-control" name="cname" />
</div>
</div>
<!--end of .form-group-->
<div class="form-group">
<label class="col-lg-2 col-md-3 control-label">Company Name</label>
<div class="col-lg-10 col-md-9">
<input type="text" required id="comname" ng-model="CusDetails.comname" class="form-control" name="comname" />
</div>
</div>
<!--end of .form-group-->
<div class="form-group">
<label class="col-lg-2 col-md-3 control-label" for="">Telephone Number</label>
<div class="col-lg-10 col-md-9">
<div class="input-group input-icon">
<span class="input-group-addon"><i class="fa fa-phone s16"></i></span>
<input ng-model="CusDetails.tel" class="form-control" id="ctel" type="text" placeholder="(999) 999-9999">
</div>
</div>
</div>
<!-- End .form-group -->
<div class="form-group">
<label class="col-lg-2 col-md-3 control-label" for="">Email address</label>
<div class="col-lg-10 col-md-9">
<input id="email" ng-model="CusDetails.email" type="text" class="form-control" name="placeholder" placeholder="someone#example.com">
</div>
</div>
<!-- End .form-group -->
</form>
</div>
</div>
<!--End .panel-->
</div>
<!--.col-9 ends here-->
</div>
<!--End .row-->
<!--Start .row-->
<div class="row">
<div class="col-md-1"></div>
<div class="col-lg-9 col-sm-9 col-xs-12">
<button id="btnSubmit" type="submit" ng-click="AddCustomer()" class="btn btn-info pad"><span class="fa fa-user-plus"></span> Add Customer</button>
<button type="submit" class="btn btn-default pad">Cancel</button>
</div>
</div>
</diV>
</div>
</div>
You can remove form field value by removing value of ng-model like
Your code
var CustDetails = {
cname: $scope.CusDetails.cname,
comname: $scope.CusDetails.comname,
tel: $scope.CusDetails.tel,
email: $scope.CusDetails.email
};
Replace with this
$scope.CustDetails = {
cname: $scope.CusDetails.cname,
comname: $scope.CusDetails.comname,
tel: $scope.CusDetails.tel,
email: $scope.CusDetails.email
};
Your code
customerForm.$setPristine(true);
Replace with this
$scope.CustDetails={};
use:
$scope.$destroy
as it removes all the children associated to the parent scope and will clear all the data associated with it.
Use
$scope.customerForm.$setPristine(true);
Give the form a name like
name= "CusDetails"
Then It will solve the problem.
Use name attr instead of id. name="forName"
The form reference inside Controller will be $scope.formName
You can set the form with the code below:
$scope.customerForm.$setPristine();
$scope.customerForm.$setUntouched();
$scope.CustDetails={};

When refresh page make sure stay in same div area

When I click on my next button and it goes to step 2 and if I reload the page I would like to make sure it stays on the same div that I am on.
The 2 divs I use are join_form_1 and join_form_2
At the moment it when I reload page it goes back to first div
How can I make it stay on the div I am on?
Codepen Example Here
$(document).ready(function(){
$("#join_form_2").hide();
$("#step_1_link").addClass("active");
$("#next").click(function(){
$("#step_1_link").removeClass("active");
$("#step_2_link").addClass("active");
$("#join_form_1").hide();
$("#join_form_2").show();
});
});
HTML
<div class="container">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="heading-message">
<div class="text-center">
<i class="fa fa-user" aria-hidden="true"></i>
</div>
<div class="text-center">
<h1>Request A Admin Member Login</h1>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-9 col-md-9 col-sm-12 col-xs-12">
<ol class="steps list-inline">
<li id="step_1_link">
Step 1: Set up a personal account
</li>
<li id="step_2_link">
Step 2: Choose profile picture
</li>
</ol>
<div id="join_form_1">
<div class="form-group">
<label>Username</label>
<input type="text" name="username" value="" class="form-control" placeholder="" />
</div>
<div class="form-group">
<label>Email</label>
<input type="text" name="email" value="" class="form-control" placeholder="" />
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" value="" class="form-control" placeholder="" />
</div>
<div class="form-group">
<label>Confirm Password</label>
<input type="password" name="confirm_password" class="form-control" placeholder="" />
</div>
<div class="form-group">
<button type="button" class="btn btn-default" id="next">Next</button>
</div>
</div><!-- Setup_1 -->
<div id="join_form_2">
<div class="form-group">
<label>Upload A Image</label>
<input type="file" name="userfile" size="50" />
</div>
</div><!-- Setup_1 -->
</div>
<div class="col-lg-3 col-md-3 col-sm-12 col-xs-12">
<div class="info-box">
<h2>You'll Love This Forum</h2>
</div>
</div>
</div>
</div>
You can use javascript cookie API here
So when user clicks 'Next'
Cookies.set('active', 'join_form_2');
Than if user clicked in the previous session, show form 2.
if (Cookies.get('active') == 'join_form_2') {
$("#join_form_1").hide();
$("#step_1_link").removeClass("active");
} else {
$("#join_form_2").hide();
$("#step_1_link").addClass("active");
}
Here is working codepen.
The easiest and most reliable way to do this is to use Fragment_identifier along with :target pseudo selector.
This will work even if cookies are disabled. And since you're using bootstrap, it's easy to style <a> tags like buttons.
For example:
if (!window.location.hash) {
window.location.hash = 'step1';
.steps:not(:target) {
display: none;
}
step1
step2
<div id="step1" class="steps">Step1</div>
<div id="step2" class="steps">Step2</div>

Categories

Resources