I have a beautiful form that has a great validation with jQuery, but where do I put the function that should run after fom was validated?
here is the form:
<form id="myForm" class=" needs-validation" novalidate>
<div class="rendered-form">
<div class="form-group row formbuilder-text form-group field-text-1650256863373">
<label for="text-1650256863373" class="col-sm-2 formbuilder-text-label">Name<span class="formbuilder-required">*</span></label>
<div class="col-sm-10">
<input type="text" class="form-control" name="text-1650256863373" access="false" maxlength="50" id="text-1650256863373" required="required" aria-required="true">
</div>
</div>
<div class="form-group row formbuilder-text form-group field-text-1650256864829">
<label for="text-1650256864829" class="col-sm-2 formbuilder-text-label">E-mail:<span class="formbuilder-required">*</span></label>
<div class="col-sm-10">
<input type="email" class="form-control" name="text-1650256864829" access="false" maxlength="30" id="text-1650256864829" required="required" aria-required="true">
<div class="invalid-feedback">e-mail</div>
</div>
</div>
<div class="form-group row formbuilder-text form-group field-text-1650256865677">
<label for="text-1650256865677" class="col-sm-2 formbuilder-text-label">Phone<span class="formbuilder-required">*</span></label>
<div class="col-sm-10">
<div class="input-group-prepend">
<div class="input-group-text">+1</div>
<input type="tel" class="form-control" name="text-1650256865677" access="false" maxlength="15" id="text-1650256865677" required="required" aria-required="true">
</div>
</div>
</div>
<div class="formbuilder-button form-group field-button-1650256992197">
<button type="submit" class="btn-success btn" name="button-1650256992197" access="false" style="success" id="button-1650256992197">Подписать</button>
</div>
</div>
</form>
here is my javascript validation:
<script>
// Example starter JavaScript for disabling form submissions if there are invalid fields
(() => {
'use strict';
// Fetch all the forms we want to apply custom Bootstrap validation styles to
const forms = document.querySelectorAll('.needs-validation');
// Loop over them and prevent submission
Array.prototype.slice.call(forms).forEach((form) => {
form.addEventListener('submit', (event) => {
if (!form.checkValidity()) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
})();
</script>
Now when user clicks one the button Submit, if the form is validated I need to show an alert window with message. Where I put it?
I assume your checkValidity() is a boolean function.
<script>
// Example starter JavaScript for disabling form submissions if there are invalid fields
(() => {
'use strict';
// Fetch all the forms we want to apply custom Bootstrap validation styles to
const forms = document.querySelectorAll('.needs-validation');
// Loop over them and prevent submission
Array.prototype.slice.call(forms).forEach((form) => {
form.addEventListener('submit', (event) => {
if(!form.checkValidity()) {
// When is invalid
alert('invalid');
event.preventDefault();
event.stopPropagation();
} else {
// When is valid
alert('valid');
}
// On form submit whether valid or invalid
alert('Was validated');
form.classList.add('was-validated');
}, false);
});
})();
</script>
Maybe you could just try to add the alert that you want at the end of your script ? It gonna be display if you script go at the end of it logic !
<script>
// Example starter JavaScript for disabling form submissions if there are invalid fields
(() => {
'use strict';
// Fetch all the forms we want to apply custom Bootstrap validation styles to
const forms = document.querySelectorAll('.needs-validation');
// Loop over them and prevent submission
Array.prototype.slice.call(forms).forEach((form) => {
form.addEventListener('submit', (event) => {
if (!form.checkValidity()) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
alert('What you want to say to user');
})();
</script>
I guess you can put it where you want, but after your logic to see if it's run fully and correctly.
Related
i'm using bootstrap's form validation to validate a form. i wan to add an extra field called discount code. this field should accept only specified codes. when the field is empty it should light green, when the code is right it should light green and when the code is wrong it should light red. how can i do that using the bootstrap form validation?
thats how my form almost looks like
<form class="needs-validation" novalidate>
<div class="form-group">
<div class="col-md-12">
<strong>Enter your name </strong>
<input type="text" name="name" id="name" class="form-control" value="" required minlength="3" />
<div class="invalid-feedback">
Name should be at least 3 characters
</div>
</div>
</div>
<div class="col-12">
<button class="btn btn-primary" type="submit">Submit form</button>
</div>
</form>
<script>
(function () {
'use strict'
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.querySelectorAll('.needs-validation')
// Loop over them and prevent submission
Array.prototype.slice.call(forms)
.forEach(function (form) {
form.addEventListener('submit', function (event) {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated')
}, false)
})
})()
</script>
I know this is a simple fix but through multiple google searches, I can't seem to find the answer to my question. I'm using a validation form from bootstrap 4, and I'm just trying to add functionality to my button by simply linking it to a different page. I tried using the anchor tag,
i.e. Submit
which will work, but the obviously validation is bypassed.
so currently I have this button within a form:
<button class="btn btn-primary" type="submit" >Submit form</button>
</form>
with this java script:
<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>
What needs to be added to the js to make the button functional?? Thank you for any assistance!!
Here's a simplified version, the code is heavily commented.
// wait for page to load then run the code inside
window.onload = () => {
// Select the form we want to validate
let form = document.querySelector('form');
// listen for submit event
form.onsubmit = (event) => {
// prevent the form from posting so the page won't refresh
event.preventDefault();
// debugging log statememnet (not needed)
console.log('Form submitted')
// checking for form validation
if (form.checkValidity() === false) {
// if we're inside this if statement, the form is invalid
// we add the boostrap class to handle styling
form.classList.add('was-validated');
// debugging log statememnet (not needed)
console.log('Form not valid')
} else {
// if we're inside this if statement, the form is valid and ready for further actions
// debugging log statememnet (not needed)
console.log('Form valid')
// redirect to the target page
location.href = "www.example.com"
}
}
};
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
<form class="needs-validation" novalidate>
<div class="form-row">
<div class="col-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-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 class="col-3">
<label for="validationCustomUsername">Username</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroupPrepend">#</span>
</div>
<input type="text" class="form-control" id="validationCustomUsername" placeholder="Username" aria-describedby="inputGroupPrepend" required>
<div class="invalid-feedback">
Please choose a username.
</div>
</div>
</div>
</div>
<button class="btn btn-primary" type="submit">Submit form</button>
</form>
If you're a beginner i suggest you stay away from libraries and just play with vanilla js/css build everything from scratch if you get stuck your research on every single line of code, Then and only then you can start messing with libraries and such.
First post here so please be gentle. I'm trying to self learn how to write a responsive website for a local club. Is there any way of checking that two password fields are identical and error accordingly using the bootstrap 4 method of form validation? I can do it server side but since I am doing a fair amount of client side form validation, it would be nice if I could check that the passwords were the same before submitting the form.
<form class="container" id="form-validation" method="post" action="./register.php" novalidate>
<div class="row">
<div class="col-md-10 mb-3">
<label for="validation1">Username</label>
<input type="text" class="form-control" name="username" id="validation1" placeholder="Username" required pattern="^[_a-zA-Z0-9\-]{5,15}$">
<div class="invalid-feedback">
Must be alpha-numeric, dash or underscore, between 5 & 15 characters
</div>
</div>
</div>
<div class="row">
<div class="col-md-10 mb-3">
<label for="validation2">Password</label>
<input type="password" class="form-control" name="pwd1" id="validation2" placeholder="Password" required pattern="^[_a-zA-Z0-9\-]{5,15}$">
<div class="invalid-feedback">
Must be alpha-numeric, dash or underscore, between 5 & 15 characters
</div>
</div>
</div>
<div class="row">
<div class="col-md-10 mb-3">
<label for="validation3">Confirm Password</label>
<input type="password" class="form-control" name="pwd2" id="validation3" placeholder="Re-enter Password" required pattern="^[_a-zA-Z0-9\-]{5,15}$">
<div class="invalid-feedback">
Must be alpha-numeric, dash or underscore, between 5 & 15 characters and match original Password
</div>
</div>
</div>
<div class="row">
<div class="col-md-10 mb-3">
<button class="btn btn-success" type="submit" value="Send" name="registerbtn">Register</button>
</div>
</div>
</form>
(function() {
"use strict";
window.addEventListener("load", function() {
var form = document.getElementById("form-validation");
form.addEventListener("submit", function(event) {
if (form.checkValidity() == false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add("was-validated");
}, false);
}, false);
}());
Using this should work.
var form = document.getElementById("form-validation");
form.addEventListener("submit", function(event) {
if ( document.getElementById("validation2").value != document.getElementById("validation3").value ) {
alert("Password mismatch");
event.preventDefault();
event.stopPropagation();
}
else if (form.checkValidity() == false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add("was-validated");
}, false);
You can achieve this validation through the JavaScript constraint validation API, it's a customError, which you can set prior to form submission.
I'll provide the example for BootStrap4 and assume jQuery as an optional but common BootStrap dependency to abbreviate $("#pw1").val()
The HTML
<form>
<div class="form-group">
<label for="pw1">Password</label>
<input type="password" class="form-control"
id="pw1" placeholder="Password"
required minLength=8>
</div>
<div class="form-group">
<label for="pw2">Repeat Password</label>
<input type="password" class="form-control"
id="pw2" placeholder="Password" aria-describedby="pwHelp"
required minLength=6
oninput="validate_pw2(this)">
<small id="pwHelp" class="form-text text-muted">Please repeat your password</small>
</div>
<button type="submit" class="btn btn-primary">Register</button>
</form>
The Script
<script>
function validate_pw2(pw2) {
if (pw2.value !== $("#pw1").val()) {
pw2.setCustomValidity("Duplicate passwords do not match");
} else {
pw2.setCustomValidity(""); // is valid
}
}
</script>
The important parts are the oninput in #pw2, which attempts to validate every time the value its changed. Then the setCustomValidity call provides the user message displayed when invalid, the empty string is used when it is now valid.
You can put a check to verify the password values are the same and abort the submission if they're not.
var form = document.getElementById("form-validation");
form.addEventListener("submit", function(event) {
if ( document.getElementById("validation2").value != document.getElementById("validation3").value ) {
alert("Password mismatch");
event.preventDefault();
event.stopPropagation();
}
else if (form.checkValidity() == false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add("was-validated");
}, false);
You would just change the alert window to show error text to your user. Here is an example to see how it would look: https://jsfiddle.net/aq9Laaew/55184/
Another suggestion would be to use something like jQuery so that the syntax is less cumbersome to deal with. But that's up to you.
From your code checkValidity() will check only the validity of the form HTML5 constraint (required, format, pattern, min, max), but there is no constraint for verify password. In reality this is like comparing if the content of 2 fields is the same. Also if you want to cancel the form submission, you also needs to return false; at the end. Normally HTML5 will not submit a form that has validation errors.
In you case I will suggest make a validation while you are typing on the validation field, and disable the submit button until the passwords match.
document.getElementById('validation3').addEventListener('keyup',function(e){
if(this.value !== document.getElementById('validation2').value){
document.getElementById('validation4').disabled=true;
this.classList.replace('pass','nopass');
}else{
document.getElementById('validation4').disabled=false;
this.classList.replace('nopass','pass');
}
}
You will need to assign an id='validation4' to the submit button. To make visual changes you could create a CSS rules to handle this ('pass','nopass').
I have a Bootstrap login form and Javascript validation:
HTML
<form id="loginForm" class="form-horizontal" role="form" action="registration.php" method="POST">
<div class="form-group">
<label class="control-label col-sm-2 modal-text" for="loginEmail">Email:</label>
<div class="col-sm-10">
<input type="email" class="form-control modal-input" id="loginEmail" placeholder="Insert email"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2 modal-text" for="loginPassword">Password:</label>
<div class="col-sm-10">
<input type="password" class="form-control modal-input" id="loginPassword" placeholder="Insert password"/>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<div class="checkbox">
<label class="modal-text"><input type="checkbox"/> Remember me</label>
</div>
</div>
</div>
<button type="button" class="btn btn-default btn-block buttons" id="loginBtn">Login</button>
</form>
And this is my Javascript validation:
function validateEmail(id){
var $div = $('#' + id).closest('div');
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(!regex.test($('#' + id).val()))
{
$div.addClass('has-error');
return false;
}
else
{
$div.removeClass('has-error');
return true;
}
}
function validateText(id){
var $div = $('#' + id).closest('div');
if($('#' + id).val() == null || $('#' + id).val() == '')
{
$div.addClass('has-error');
return false;
}
else
{
$div.removeClass('has-error');
return true;
}
}
$(document).ready(function (){
$('#loginBtn').click(function (){
if(!validateEmail('loginEmail'))
{
return false;
}
if(!validateText('loginPassword'))
{
return false;
}
$('form#loginForm').submit();
});
});
If I press login button, form submits immediately even if fields are empty.Is there something I'm missing or doing wrong?
UPDATE
What I discovered is that I put quotes around my regex expression which caused javascript error. I also changed button type from submit to button. Now it is working.
So to sum up: My validation didn't work because of quotes in regular expression. Validation will work even if I left button type submit.
Use onsubmit instead of onclick, and return true when the form is valid.
In your case, the onclick event will be fired, correctly return false, and then as the button is still a submit type, it will still submit the form.
It submits anyway, because the button is a submit button:
<button type="submit"
The return false from the click handler cancels the click event, but no other events - ie the submit event still fires.
You can change the button to type=button and then submit the form in the click handler (which you're already doing):
<button type="button"
You have used button with type="submit" and method="POST". So, when you click button it is immediately submitting form. Try type="button" for your submit button.
Stop event handling, probably you don't want to do anything else than to submit form if it is valid
$('#loginBtn').click(function (Evt){
Evt.stopPropagtion();
Evt.preventDefault();
if(!validateEmail('loginEmail'))
{
return false;
}
if(!validateText('loginPassword'))
{
return false;
}
$('form#loginForm').submit();
});
I am trying to use browser validation messaging. I am not able to define a custom message when 2 fields are NOT identical.
My situation is that i have to test when the field IS valid, so i used jquery on.blur to test, but for some reason, the message is empty.
Try entering 2 valid but different email addresses. The expected result is supposed to be "Test why not working" has a browser message.
Working jsFiddle of my situation
HTML:
<form id="newsletter_form" class="form" role="form" name="newsletter_form" method="post" action="/" autocomplete="off">
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6">
<input type="email" class="form-control" name="email" id="email" value="" maxlength="250" placeholder="email" aria-required="true" required="required" />
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6">
<input type="email" class="form-control" name="confirm_email" id="confirm_email" value="" maxlength="250" placeholder="confirm email" aria-required="true" required="required" />
</div>
</div>
<input type="submit" class="btn submit btn-default" value="submmit!" />
</form>
JAVASCRIPT:
$('form #email').on('change invalid', function () {
var field = $(this).get(0);
field.setCustomValidity('');
if (!field.validity.valid) {
field.setCustomValidity("custom email invalid");
}
});
/* THIS IS MY BUGGY ONE */
$('form #confirm_email').on('blur valid', function () {
var field = $(this).get(0);
field.setCustomValidity('');
if ($("#email").val() != $("#confirm_email").val()) {
/* i tried setting the field to invalid, nothing */
//field.validity.invalid;
//alert('s');
field.setCustomValidity("test why not working");
}
});
$('form #confirm_email').on('change invalid', function () {
var field = $(this).get(0);
field.setCustomValidity('');
if (!field.validity.valid) {
field.setCustomValidity("custom error message");
}
});
I tried jquery.on(change valid .. and so on, i get the alert() bot not the changed text.
Any help will be appreciated, i am getting bored of this 'bug'?
but for some reason, the message is empty.
That is because you are explicitly setting it to be empty:
field.setCustomValidity('');
in your "custom error message" handler that is used to grump about the invalid email. That handler is executed after the 'blur valid', and will always reset what happened before. You can try it by uncommenting above line.
Any help will be appreciated
Check both reasons in the same handler:
$('form #confirm_email').on('change valid invalid', function () {
// var field = $(this).get(0); -- don't do this!!! field = this.
this.setCustomValidity('');
if (!this.validity.valid) {
this.setCustomValidity("custom message for standard errors");
} else if ($("#email").val() != this.value) {
this.setCustomValidity("test now working");
}
});
(updated demo)