Bootstrap form validation in jQuery instead of plain JavaScript? - javascript

I found this on Bootstrap to use Bootstrap form validation. Why is the example in plain JavaScript instead of jQuery when the rest of Bootstrap scripts are in jQuery?
How can this be done with jQuery?
https://getbootstrap.com/docs/4.0/components/forms/#validation
<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>

use Jquery Validation : https://jqueryvalidation.org/documentation/
$(document).ready(function(){
$('#contact-form').validate({
rules: {
'checkbox': {
required: true
}
},
highlight: function (input) {
$(input).addClass('is-invalid');
},
unhighlight: function (input) {
$(input).removeClass('is-invalid');
},
errorPlacement: function (error, element) {
$(element).next().append(error);
}
});
});
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/jquery-validation#1.17.0/dist/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<form id="contact-form" method="POST" action="/contact">
<div class="form-group">
<input type="text" class="form-control" name="name" placeholder="Name" id="name" class="form-control" autocomplete='name' value="" required>
<div class="invalid-feedback"></div>
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" placeholder="Email" id="email" class="form-control" autocomplete='email' value="" required>
<div class="invalid-feedback"></div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="phone" placeholder="Phone" id="phone" class="form-control" autocomplete='tel' value="" required>
<div class="invalid-feedback"></div>
</div>
<div class="form-group">
<textarea placeholder="Message" class="form-control" name="message" rows="5" class="form-control" required></textarea>
<div class="invalid-feedback"></div>
</div>
<div class="container-contact-form-btn">
<button class="btn btn-primary" type="submit">
Send Now
</button>
</div>
</form>

$(document).ready(function(){
$('.needs-validation').on('submit', function(e) {
if (!this.checkValidity()) {
e.preventDefault();
e.stopPropagation();
}
$(this).addClass('was-validated');
});
});

This example was most likely written in JS as that's what the author of the Bootstrap documentation was most comfortable with. You can convert it to jQuery like this:
(function() {
'use strict';
$(window).on('load', function() {
$('.needs-validation').on('submit', function(e) {
if (!this.checkValidity()) {
e.preventDefault();
e.stopPropagation();
}
$(this).addClass('was-validated');
});
});
})();

Related

Bootstrap 4 manually invalidate input field natively

I want to make use of Bootstrap 4's form validation. From what I read you can invalidate a field by adding class 'is-invalid' - this works, but when I want to check the form validity using method checkValidity() it still says the form is VALID which is not what I expected. I was hoping of making use of the native bootstrap 4 functionality and not use plugins such as jquery validator etc.
$('#submit_button').on('click', function(e){
var forms = document.getElementsByClassName('needs-validation');
var validation = Array.prototype.filter.call(forms, function(form) {
if (form.checkValidity() === false) {
console.log("form is INVALID")
event.preventDefault();
event.stopPropagation();
} else {
console.log("form is VALID")
}
// form.classList.add('was-validated');
});
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.3/css/bootstrapValidator.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<head>
</head>
<body>
<form class="needs-validation" id="my_form">
<div class="form-group">
<div class="form-check">
<label for="taskname_l">Task Name</label>
<div class="form-inline">
<input type="text" class="form-control task_form is-invalid" id="taskname_in" name="taskname_in">
</div>
</div>
</div>
<button class="btn btn-primary" type="button" id="submit_button">Submit form</button>
</form>
</body>
Option 1:
Using JQUERY you can use the .val() function
To get the value of the input field with id "taskname_in" use this code
$('#taskname_in').val()
Option 1 snippet:
$('#submit_button').on('click', function(e) {
var forms = document.getElementsByClassName('needs-validation');
var validation = Array.prototype.filter.call(forms, function(form) {
if ($('#taskname_in').val() == '') {
console.log("form is INVALID")
event.preventDefault();
event.stopPropagation();
} else {
console.log("form is VALID")
}
// form.classList.add('was-validated');
});
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.3/css/bootstrapValidator.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<head>
</head>
<body>
<form class="needs-validation" id="my_form">
<div class="form-group">
<div class="form-check">
<label for="taskname_l">Task Name</label>
<div class="form-inline">
<input type="text" class="form-control task_form" id="taskname_in" name="taskname_in">
</div>
</div>
</div>
<button class="btn btn-primary" type="button" id="submit_button">Submit form</button>
</form>
</body>
Option 2:
Using form validator to check all input-fields at once.
Option 2 snippet:
(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);
})();
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.3/css/bootstrapValidator.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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>
<div class="col-md-4 mb-3">
<label for="validationCustom02">Last name</label>
<input type="text" class="form-control" id="validationCustom02" placeholder="Last name" value="" required>
<div class="valid-feedback">Looks good!</div>
</div>
</div>
<button class="btn btn-primary btn-sm" type="submit">Submit form</button>
</form>
'is-invalid' does not make that particular field an invalid. it just applies CSS to look as it's invalid.
Result of HTMLElement.checkValidity() depends on its Constraint.
Suppose, you add field with 'required' constrain and you run checkValidity() on the form or field while it's empty, you will receive response as false, which means that a form or field is not valid.
In your case, just add required in your input field and you will receive response as invalid if you submit form while field is empty.
If you have the default Bootstrap validation code for the required fields:
$(".needs-validation").submit(function() {
var form = $(this);
if (form[0].checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.addClass('was-validated');
});
You would just need to add another validation for example on input and use the setCustomValidity. For example if you want to check for equal values on password and confirm password:
if ($('form input[name="confirm_password"').length > 0) {
$('input[name="confirm_password"').on('change paste keyup', function() {
var password = $(this).closest('form').find('input[name="password"').val();
if($(this).val() !== password){
this.setCustomValidity('Passwords must match');
} else {
this.setCustomValidity('');
}
});
};
If you have an invalid-feedback message next to the input element it will show that message instead of the one you set here.

jQuery validation does not validate my textarea element

I am currently using jQuery validation to validate my fields. I've two fields,
named "comments" & "account name". Both fields have the same rule method where required is true. When I click the "save" button, only the account name was validated. Why is that so? Here is a screenshot of my problem and my codes
$(document).ready(function() {
$.validator.setDefaults({
errorClass: 'help-block',
highlight: function(element) {
$(element)
.closest('.form-group')
.addClass('has-error');
},
unhighlight: function(element, errorClass, validClass) {
$(element)
.closest('.form-group')
.removeClass('has-error')
.addClass('has-success');
},
});
$('#dataForm').validate({
rules: {
commentInput: {
required: true
},
accountNameInput: {
required: true
}
},
submitHandler: function(form) {
alert('success');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/js/bootstrap.min.js"></script>
<form id="dataForm" method="post" action="#">
<div class="form-group">
<label class="control-label" for="commentInput">Comments</label>
<textarea class="commentInput" id="commentInput" cols="20" rows="5"></textarea>
</div>
<div class="form-group">
<label class="control-label" for="accountNameInput">Account name</label>
<input type="text" id="accountNameInput" name="accountNameInput" placeholder="Account name" class="form-control font-bold" value="" />
</div>
<input type="submit" class="btn btn-primary" value="Save" id="saveButton" />
</form>
You have to give all form fields that need validation a name attribute. That's where the validation plugin gets the reference to the element from.
From the documentation:
Throughout the documentation, two terms are used very often, so it's
important that you know their meaning in the context of the validation
plugin:
method: A validation method implements the logic to validate an element, like an email method that checks for the right format of a
text input's value. A set of standard methods is available, and it is
easy to write your own.
rule: A validation rule associates an element with a validation method, like "validate input with name "primary-mail" with
methods "required" and "email".
The name attribute is also required to be present on any form field that will need to transmit its data as part of the form submission.
$(function() {
$.validator.setDefaults({
errorClass: 'help-block',
highlight: function(element) {
$(element)
.closest('.form-group')
.addClass('has-error');
},
unhighlight: function(element, errorClass, validClass) {
$(element)
.closest('.form-group')
.removeClass('has-error')
.addClass('has-success');
},
});
$('#dataForm').validate({
rules: {
commentInput: {
required: true
},
accountNameInput: {
required: true
}
},
submitHandler: function(form) {
alert('success');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/js/bootstrap.min.js"></script>
<form id="dataForm" method="post" action="#">
<div class="form-group">
<label class="control-label" for="commentInput">Comments</label>
<textarea class="commentInput" id="commentInput" name="commentInput" cols="20" rows="5"></textarea>
</div>
<div class="form-group">
<label class="control-label" for="accountNameInput">Account name</label>
<input type="text" id="accountNameInput" name="accountNameInput" placeholder="Account name" class="form-control font-bold" value="" />
</div>
<input type="submit" class="btn btn-primary" value="Save" id="saveButton" />
</form>
The validation plugin targets by the name attribute:
<textarea id="commentInput" name="commentInput" cols="20" rows="5"></textarea>
You need use the name attribute for validate.
$(document).ready(function() {
$.validator.setDefaults({
errorClass: 'help-block',
highlight: function(element) {
$(element)
.closest('.form-group')
.addClass('has-error');
},
unhighlight: function(element, errorClass, validClass) {
$(element)
.closest('.form-group')
.removeClass('has-error')
.addClass('has-success');
},
});
$('#dataForm').validate({
rules: {
commentInput: {
required: true
},
accountNameInput: {
required: true
}
},
submitHandler: function(form) {
alert('success');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/js/bootstrap.min.js"></script>
<form id="dataForm" method="post" action="#">
<div class="form-group">
<label class="control-label" for="commentInput">Comments</label>
<textarea name="commentInput" class="commentInput" id="commentInput" cols="20" rows="5"></textarea>
</div>
<div class="form-group">
<label class="control-label" for="accountNameInput">Account name</label>
<input type="text" id="accountNameInput" name="accountNameInput" placeholder="Account name" class="form-control font-bold" value="" />
</div>
<input type="submit" class="btn btn-primary" value="Save" id="saveButton" />
</form>

Onsubmit in form does not called

I have next form:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function submit(form) {
var first_pass = form.find('.first_try');
var second_pass = form.find('.second_try');
if (first_pass.value == second_pass.value) {
return true
}
first_pass.value = '';
second_pass.value = '';
first_pass.attr('placeholder', 'Пароли не совпадают');
first_pass.css('border-color', 'red');
second_pass.css('border-color', 'red');
return false
}
</script>
<form role="form" method="post" onsubmit="return submit($('#PasswordChange form'))">
<h3>Редактирование пользователя</h3>
<div class="form-group">
<input type="password" class="form-control first_try" name="password"
placeholder="Новый пароль"
required>
</div>
<div class="form-group">
<input type="password" class="form-control second_try" name="password"
placeholder="Повтор пароля"
required>
</div>
<input type="submit" name="submit" class="btn btn-primary pull-right" value="Отправить"></input>
</form>
This script checks whether passwords are the same.
But using firefox debugger i can't find that it goes into this method.
Is this problem with script? Or Is ths problem about declaring onsubmit handler?
There was many problems:
change value to val
use another name for submit function, it's kinda reserved
use this instead of $('#PasswordChange form')
use var first_pass = $('.first_try'); instead of find
you forgot to write else
and you need use event.preventDefault(); to stop refreshing page or submiting page.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function save(form) {
var first_pass = form.querySelector('.first_try');
var second_pass = form.querySelector('.second_try');
if (first_pass.value == second_pass.value) {
alert('its ok');
return true;
} else {
first_pass.value = '';
second_pass.value = '';
first_pass.placeholder = 'Пароли не совпадают';
first_pass.style.borderColor='red';
second_pass.style.borderColor='red';
return false
}
}
</script>
<form role="form" method="post" onsubmit="event.preventDefault(); return save(this)">
<h3>Редактирование пользователя</h3>
<div class="form-group">
<input type="password" class="form-control first_try" name="password"
placeholder="Новый пароль"
required>
</div>
<div class="form-group">
<input type="password" class="form-control second_try" name="password"
placeholder="Повтор пароля"
required>
</div>
<input type="submit" name="submit" class="btn btn-primary pull-right" value="Отправить"/>
</form>
Use this code
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
function submitData(form) {
var first_pass = form.find('.first_try');
var second_pass = form.find('.second_try');
if (first_pass.value == second_pass.value) {
return true
}
first_pass.value = '';
second_pass.value = '';
first_pass.attr('placeholder', 'Пароли не совпадают');
first_pass.css('border-color', 'red');
second_pass.css('border-color', 'red');
return false
}
</script>
</head>
<body>
<form role="form" method="post" onsubmit="return submitData($('#PasswordChange form'))">
<h3>Редактирование пользователя</h3>
<div class="form-group"> <input type="password" class="form-control first_try" name="password" placeholder="Новый пароль" required></div>
<div class="form-group"> <input type="password" class="form-control second_try" name="password" placeholder="Повтор пароля" required></div><input type="submit" name="submit" class="btn btn-primary pull-right" value="Отправить"></form>
</body>
</html>
Please change submit function name because it is keyword so it is not use it. Also remove </input> next to submit button
Use this :
onsubmit="return submit(this)"
You should not return anything if you don't need to cancel the submit action. Also you could use submit form event handler with jQuery .submit() method instead of hanler definition in onsubmit attribute.
$("form").submit(function(e) {
var passwords = $('[name=password]');
if (passwords.eq(0).val() !== passwords.eq(1).val()) {
alert("Пароли не совпадают!");
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form role="form" method="post" action="/">
<h3>Редактирование пользователя</h3>
<div class="form-group">
<input type="password" class="form-control first_try" name="password" placeholder="Новый пароль" required >
</div>
<div class="form-group">
<input type="password" class="form-control second_try" name="password" placeholder="Повтор пароля" required />
</div>
<input type="submit" name="submit" class="btn btn-primary pull-right" value="Отправить" />
</form>
Also I recommend you to use Bootstrap validation states instead of input's border style setting.

Validate fields using jquery

I'm creating a form that requires to enter some fields.
The basic required attribute won't work on me, so I would like to use jQuery.
Then when those fields were already filled, the submit button will be enabled.
here's my code:
$(function() {
$('#catalog_order').validate(
{
rules:{
schedule: {
required: true
}
},
messages:{
schedule: "Please indicate schedule",
}
});
$('#checkin input').on('keyup blur', function (e) { // fires on every keyup & blur
if ($('#checkin').valid()) {
$('#submit').attr('disabled', false);
}
else {
$('#submit').attr('disabled', true);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.js"></script>
<form role="form" id="checkin" name="checkin" method="post">
<label for="dedicatalog"> Dedication Text: </label> <input type="text" name="dedicatalog" id="dedicatalog" size="20" placeholder="Dedication" /> <!-- NOT REQUIRED, but still disable the CHECK IN NOW-->
<label for="schedule"> Date: </label> <input type="date" id="schedule" name="schedule" value="M-D-YY"/> <!-- REQUIRED -->
<label for="figurine_select"> Figurine/s: </label> <!-- NOT REQUIRED, but still disable the CHECK IN NOW-->
<select name="figurine_sel" id="figurine_select" />
<option selected value=" ">--Figurines--</option>
<option value="angel">Angel</option>
<option value="teletubies">Teletubies</option>
</select>
<input type="submit" id="submit" class="btn btn-default" value="Check In Now" disabled="disabled" />
</form>
Hope someone can help me out.
Thank you!!
This Fiddle Should work
Note that for every field you should specify all its option inside js object ( between brackets )
schedule: {
required: true
},
Below working snippet
jQuery.validator.addMethod("dateFormat", function(value, element) {
console.log(value,/^(0?[1-9]|1[0-2])\/(0?[1-9]|1[0-9]|2[0-9]|3[01])\/\d{2}$/.test(value));
return /^(0?[1-9]|1[0-2])\/(0?[1-9]|1[0-9]|2[0-9]|3[01])\/\d{2}$/.test(value);
}, "Invalid Date !");
$(function() {
$('#checkin').validate(
{
rules:{
schedule: {
required:true,
dateFormat: true,
}
},
messages:{
required:"Required Field !"
}
});
$('#checkin input').on('keyup blur', function (e) { // fires on every keyup & blur
if ($('#checkin').valid()) {
$('#submit').attr('disabled', false);
}
else {
$('#submit').attr('disabled', true);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.js"></script>
<form role="form" id="checkin" name="checkin" method="post">
<label for="dedicatalog"> Dedication Text: </label> <input type="text" name="dedicatalog" id="dedicatalog" size="20" placeholder="Dedication" />
<label for="schedule"> Date: </label> <input id="schedule" name="schedule" placeholder="M-D-YY"/>
<input type="submit" id="submit" class="btn btn-default" value="Check In Now" disabled />
</form>
This is how I validate that.
return false is just the same us disabling it
<form role="form" id="checkin" name="checkin" method="post">
<input id="dedicatalog"/>
<input id="date" type="date"/>
</form>
<script>
$('#checkin').on('submit', function() {
var dedicatalog = $.trim($('#dedicatalog').val());
var date = $.trim($('#date').val());
if(dedicatalog == '' || date == '') {
return false;
}
});
</script>
You can use the invalidHandler parameter to check for any invalid fields:
invalidHandler: function(event, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
$('#button').hide();
} else {
$('#button').show();
}
}

Issue in jquery validator popup message

I want to create some popup that will tell user when he doesn't enter name, lastname, number or email.
HTML :
<div class="form-group">
<label class="label-block" for="cname" data-new-placeholder="What is your name?">Ime</label>
<input name="firstName" minlength="3" type="text" required class="texbox">
</div>
<div class="form-group">
<label class="label-block" for="cemail">Email</label>
<input name="ctct" type="email" required="required" required class="texbox">
</div>
</div>
<div class=" col-md-6">
<div class="form-group">
<label class="label-block">Prezime</label>
<input name="lastName" type="text" required class="texbox">
</div>
<div class="form-group">
<label class="label-block">Telefon</label>
<input name="number" type="digits" required class="texbox">
</div>
</div>
JS :
<script src="scripts/jquery.validationEngine-en.js" type="text/javascript" charset="utf-8"></script>
<script>
$(document).ready(function () {
$("#configuration-form").validate({
messages: {
name: {
required: "Error!"
}
}
});
});
</script>
<script>
$("#commentForm").validate();
</script>
That is my code in html and css... I managed to make my textbox turns red when the email is not ok. how to create that popup text.
It looks like you are using Twitter Bootstrap, and they have a popover feature or alert message that you can use: Bootstrap - popovers
HTML :-
Validation for Email.
<input type="text" id="email">
<input type="submit" onclick="validateEmail()" >
JavaScript Code :-
function validateEmail() {
var emailText = document.getElementById('email').value;
var pattern = /^[a-zA-Z0-9\-_]+(\.[a-zA-Z0-9\-_]+)*#[a-z0-9]+(\-[a-z0-9]+)*(\.[a-z0-9]+(\-[a-z0-9]+)*)*\.[a-z]{2,4}$/;
if (pattern.test(emailText)) {
return true;
} else {
alert('Bad email address: ' + emailText);
document.getElementById("email").style.backgroundColor = "Red";
return false;
}
}
Working Demo for Email Validation.
I hope it will help you.

Categories

Resources