add customized field for bootstrap validation modal - javascript

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>

Related

how to submit the form after validation

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.

Adding functionality to submit button within validation form - Bootstrap 4

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.

Submit form although field is required-> used Bootstrap Checkout example

i created a simple form to submit a text.
This text inpout is required.
But if I click on the submit button the form is sent even though the required text is empty.
I used this bootstrap example template
// 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
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)
}())
$("#suche").submit(function(event) {
alert("Handler for .submit() called.");
event.preventDefault();
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
<div class="row">
<div id="karte1" class="col-md-7 order-md-1">
<form class="needs-validation" id="suche" novalidate>
<div class="mb-3">
<div class="input-group">
<input type="text" class="form-control" id="username2" required>
<div class="input-group-append">
<button type="submit" class="btn btn-outline-secondary">
submit
</button>
</div>
<div class="invalid-feedback" style="width: 100%;">
Valid text is required.
</div>
</div>
</div>
</form>
</div>
<!-- Karte1 -->
</div>
<!-- row -->
</div>
<!-- container -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>
Thanks for your help!
Could you maybe use the html required attribute instead?
This should be a comment but I do not have enough reputation.

Prevent angular form from submitting if input is blank

I have an Angular form inside a ng2 popup:
<popup>
Sign up for our Newsletter! <form #f="ngForm" (ngSubmit)="onSubmit()" novalidate>
</button> <input type="email"/>
<button>Submit</button>
</form>
</popup>
<button class="submit" (click)="ClickButton()">Sign up for our Newsletter </button>
here is the onClick event function:
constructor(private popup:Popup) { }
testAlert() { ClickButton(){
alert("Newsletter event works"); this.popup.options = {
widthProsentage: 15,
showButtons: false,
header: "Sign up for our Newsletter!",
}
this.popup.show(this.popup.options);
}
It works fine but I am able to submit her even if the input is blank, how can I make so that it does not submit if it is clicked empty
I tried using RegEx but it did not work
Consider adding validation.
Something like this:
<div class="form-group row">
<label class="col-md-2 col-form-label"
for="userNameId">User Name</label>
<div class="col-md-8">
<input class="form-control"
id="userNameId"
type="text"
placeholder="User Name (required)"
required
(ngModel)="userName"
name="userName"
#userNameVar="ngModel"
[ngClass]="{'is-invalid': (userNameVar.touched || userNameVar.dirty) && !userNameVar.valid }" />
<span class="invalid-feedback">
<span *ngIf="userNameVar.errors?.required">
User name is required.
</span>
</span>
</div>
</div>
You can then disable the submit button if the fields are not valid:
<button class="btn btn-primary"
type="submit"
style="width:80px;margin-right:10px"
[disabled]="!loginForm.valid">
Log In
</button>
(ngSubmit) is built-in event emitter inside of Angular ngForm and is directly related to button element which is kind of a trigger for form submission.
Therefore, as lealceldeiro said, you only need onSubmit function and button intended for submission inside of your form tag.
Please provide live demo so we can see the whole file (.ts particularly).
Setting the validation properly depends on what kind of forms you're going to use (template or ReactiveForms).
See more about proper ngForm usage in official documentation.

form.checkValidity checking that two password fields match

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').

Categories