Bootstrap V5 Form Validation & Sweetalert2 : Showing success message after successful submission - javascript

I have simple form based on Bootstrap 5 with a validation option I'm trying to display alert message if the form field is successfuly submited using Sweatalert2.
Here is my Code :
HTML
<form action="" method="POST" class="needs-validation" novalidate>
<label for="validationCustomUsername" class="form-label">Username</label>
<div class="input-group has-validation mb-3">
<span class="input-group-text" id="inputGroupPrepend">#</span>
<input type="text" class="form-control" id="validationCustomUsername" placeholder="Username *" aria-describedby="inputGroupPrepend" required />
<div class="invalid-feedback">
Please choose a username.
</div>
</div>
<button class="btn btn-primary" type="submit">Submit form</button>
</form>
JS
(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)
})
})()
Live Example

I was having the same issue and came across this post which quite helpful.
Below code might help:
......
form.classList.add('was-validated');
if (form.reportValidity()) {
event.preventDefault()
Swal.fire({
position: 'center',
icon: 'success',
title: 'Your application has been submitted successfully!',
showConfirmButton: false,
timer: 2500
}).then((result) => {
// Reload the Page
location.reload();
});
}
It will reload the page after form submission.

This is may be too late, but I hope it can help others. I have the same issue. Then, I tried to combine bootstrap validation inside the SweetAlert Confirmation Box before submitting the form.
I create the code like below:
$('#submitForm').on('click', function (e) {
e.preventDefault();// prevent form submit
/*this part is taken from bootstrap validation*/
var forms = document.getElementsByClassName('needs-validation');
var validation = Array.prototype.filter.call(forms, function (form) {
if (form.checkValidity() === false) {
form.classList.add('was-validated');
}
else {
Swal.fire({
title: 'Are you sure?',
text: "It cannot be undone",
type: 'warning',
icon: 'question',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, send it!'
}).then((result) => {
if (result.value) {
/*submit the form*/
$("#formsubmitsekali").submit();
}
});
}
}, false);
});
submitForm is the ID name for the button ID for submit the form.
formsubmitsekali is the form ID.
By doing so, if the required field is not filled, it will show the bootstrap validation without showing Sweetalert confirmation box. But if all of required fields are filled, the Sweetalert will show up.
The same behavior also happens if you have email input type, but it is filled by non-email, it will run the bootstrap validation first. It is also work if you use HTML5 pattern inside the input type and the user fills with the wrong pattern.

Related

Prime-NG Confirm Dialog: Hide the Button after Confirmation

I'm struggling with a problem using Angular and PrimeNG.
There is an Input Field for weight allowing numbers up to 150. If the typed in value is greater than 150, a Confirm Button appears below the Input Field.
If this button is clicked, the Confirm Dialog pops up, asking "Are you sure?". It contains two buttons to choose from, "Yes" and "No".
1.) Choosing "No" should close the Confirm Dialog and delete the previously typed-in value in the input field (this works). The Confirm Button shall vanish (fails).
2.) Choosing "Yes" should close the Confirm Dialog and leave the typed-in value (this works). Confirm button shall vanish (also fails).
Is it somehow possible to let the button disappear after the Confirm Dialog is closed?
test.component.html:
<div class="p-col-12 p-md-6 p-lg-5">
Weight:
<div class="ui-inputgroup">
<input pInputText type="number" id="weight" name="weight" [(ngModel)]="newTest.testWeight"
placeholder="---">
<span class="ui-inputgroup-addon">kg</span>
</div>
<div *ngIf="validateIfWeightOutsideRange()">
<div>
<p-confirmDialog key="confirmWeightTest"></p-confirmDialog>
<button type="button" (click)="confirmWeightTest()" pButton icon="pi pi-check"
label="Please confirm!">
</button>
<p-messages [value]="messagesWeightTest"></p-messages>
</div>
</div>
</div>
test.component.ts
messagesWeightTest: Message[] = [];
confirmWeightTest() {
this.confirmationService.confirm({
message: 'Are you sure?',
header: 'Confirmation',
icon: 'pi pi-exclamation-triangle',
key: 'confirmWeightTest',
accept: () => {
this.messagesWeightTest = [{
severity: 'info', summary: 'Confirmed', detail: 'The input is correct.'}];
},
reject: () => {
this.sessionService.newTest.testWeight = null;
}
});
}
Please note: The method "validateIfWeightOutsideRange()" works, therefore I think it's unnecessary to show it here.
Here is the link to PrimeNG's documentation: https://www.primefaces.org/primeng/#/confirmdialog
Maybe you have an idea?
You can simply take one bool variable and set it on confirmDialog button click
messagesWeightTest: Message[] = [];
public weightConfirmed: boolean = false;
confirmWeightTest() {
this.confirmationService.confirm({
message: 'Are you sure?',
header: 'Confirmation',
icon: 'pi pi-exclamation-triangle',
key: 'confirmWeightTest',
accept: () => {
this.messagesWeightTest = [{
severity: 'info', summary: 'Confirmed', detail: 'The input is correct.'}];
this.weightConfirmed = true;
},
reject: () => {
this.sessionService.newTest.testWeight = null;
this.weightConfirmed = true;
}
});
}
<div *ngIf="validateIfWeightOutsideRange()">
<div>
<p-confirmDialog key="confirmWeightTest"></p-confirmDialog>
<button *ngIf="!weightConfirmed" type="button" (click)="confirmWeightTest()" pButton icon="pi pi-check"
label="Please confirm!">
</button>
<p-messages [value]="messagesWeightTest"></p-messages>
</div>
</div>

Javascript unobtrusive onclick with sweetalert

Good Evening,
I'm fairly new to JavaScript. I have a book and scour the internet when looking for answers. I see that the JavaScript landscape seems to have a plethora of paths and frameworks. To the question, I'm trying to use unobtrusive javascript with sweetalert. I had an issue with onclick finishing the function before an option was selected. I altered the function to return false by default and let the path nullify the onlick function and click the button. Is the following reasonable form ? Or would another method be recommended for the same effect? If so, please indicate why its better. Also, no framework/library answers for the moment please.
window.onload = function() {
function doSomething() {
var button = document.getElementById("edit");
swal({
title: 'Are you sure?',
text: 'You will not be able to recover this imaginary file!',
type: 'warning',
showCancelButton: true,
confirmButtonText: 'Yes, Update it!',
cancelButtonText: 'No, stop'
}).then((result) => {
if (result.value) {
button.onclick = null;
button.click();
// For more information about handling dismissals please visit
// https://sweetalert2.github.io/#handling-dismissals
} else if (result.dismiss === swal.DismissReason.cancel) {
swal(
'Cancelled',
'No Update Occured :)',
'error'
)
}
})
return false;
}
document.getElementById("edit").onclick = doSomething;
<form action="{{route('categories.update',$cat->id)}}" method="post">
{{method_field('patch')}}
<div class="form-group">
<label for="title">Name</label>
<input type="text" name="name" class="form-control" value="{{$cat->name}}">
<label for="description">Description</label>
<input type="text" name="description" class="form-control" value="{{$cat->description}}">
</div>
<button class="btn btn-primary" type="submit" id="edit">Edit Category</button>
{{#csrf_field()}}
</form>

Braintree JSv3 payment_method_nonce Value Bad With HostedFields

I have looked at a few posts on here with the same issue but under different circumstances that don't supply me with an answer to my particular issue...
I was using Braintree JSv2 with my Django project and all was working fine. Since I have migrated over to v3 of Braintree, the only issue I seem to have right now is that the value inputted to "payment_method_nonce" is not there...
Here is the code that is supposed to be dumping the payment_method_nonce value:
document.querySelector('input[name="payment_method_nonce"]').value = payload.nonce;
And here is the code that is supposed to be grabbing it on the python side:
client_payment_nonce = request.POST['payment_method_nonce']
When submitting this in my dev environment, I get an error (MultiValueDictKeyError) for "payment_method_nonce".
I am using Django 1.9 and Python 2.7. I am also using the example given by Braintree for a simple integration using HostedFields...
Small test
So I manually added an input field in my form with name "payment_method_nonce" just to see if not having a field was causing some issue. I know it is injected by Braintree but just testing a thought. It seems that although the value of payment_method_nonce is supposed to be my nonce, I didn't type anything into the input box and it was still coming back as null.
Full Snippets of Form and HostedFields
<form action="/booking/" method="post" id="checkout_form">
{% csrf_token %}
<div class="payment">
<span>Payment</span>
<!--input elements for user card data-->
<div class="hosted-fields" id="card-number"></div>
<div class="hosted-fields" id="postal-code"></div>
<div class="hosted-fields" id="expiration-date"></div>
<div class="hosted-fields" id="cvv"></div>
<div class="btns">
<input type="hidden" name="payment_method_nonce">
<input type="submit" value="Complete Booking" id="pay-button">
</div>
</div>
</form>
Note: I had just changed the payment_method_nonce field to type="hidden" instead of type="text" but still have the same effect...
<!-- load the required client component -->
<script src="https://js.braintreegateway.com/web/3.15.0/js/client.min.js"></script>
<!-- load the hosted fields component -->
<script src="https://js.braintreegateway.com/web/3.15.0/js/hosted-fields.min.js"></script>
<!-- Braintree setup -->
<script>
var client_token = "{{ request.session.braintree_client_token }}"
var form = document.querySelector('#checkout-form');
var submit = document.querySelector('input[type="submit"]');
braintree.client.create({
authorization: client_token
}, function (clientErr, clientInstance) {
if (clientErr) {
// Handle error in client creation
return;
}
braintree.hostedFields.create({
client: clientInstance,
styles: {
'input': {
'font-size': '14px'
},
'input.invalid': {
'color': 'red'
},
'input.valid': {
'color': 'green'
}
},
fields: {
number: {
selector: '#card-number',
placeholder: 'Credit Card Number'
},
cvv: {
selector: '#cvv',
placeholder: '123'
},
expirationDate: {
selector: '#expiration-date',
placeholder: '10/2019'
},
postalCode: {
selector: '#postal-code',
placeholder: '10014'
}
}
}, function (hostedFieldsErr, hostedFieldsInstance) {
if (hostedFieldsErr) {
// handle error in Hosted Fields creation
return;
}
submit.removeAttribute('disabled');
form.addEventListener('submit', function (event) {
event.preventDefault();
hostedFieldsInstance.tokenize(function (tokenizeErr, payload) {
if (tokenizeErr) {
// handle error in Hosted Fields tokenization
return;
}
// Put `payload.nonce` into the `payment_method_nonce`
document.querySelector('input[name="payment_method_nonce"]').value = payload.nonce;
document.querySelector('input[id="pay-button"]').value = "Please wait...";
form.submit();
});
}, false);
});
});
</script>
Note: the line document.querySelector('input[id="pay-button"]').value = "Please wait..."; doesn't fire (I know this because the button does not change values). Maybe these querySelector lines just aren't working?
Something New Noticed
I just went back to my page and hit the submit button without even entering any information. In v2 of Braintree, I would not be able to click the submit button until all fields were filled in... Maybe the values in my form aren't even being sent to braintree to receive a nonce and that's why there is an empty string being returned..?
Moral of the story
Review your code... Multiple times. As pointed out by C Joseph, I have my form ID as something different than what my var form is referencing...
<form action="/booking/" method="post" id="checkout_form">
var form = document.querySelector('#checkout-form');

Braeintree Client Set Up with JS v3 - payment_method_nonce null and the form isn't submitting

I've tried to integrate Braintree in my Laravel 5.2 app and everything works fine with JS v2 client setup, but I would like to upgrade it to v3.
This is from the docs (I've customized a bit):
<form id="checkout-form" action="/checkout" method="post">
<div id="error-message"></div>
<label for="card-number">Card Number</label>
<div class="hosted-field" id="card-number"></div>
<label for="cvv">CVV</label>
<div class="hosted-field" id="cvv"></div>
<label for="expiration-date">Expiration Date</label>
<div class="hosted-field" id="expiration-date"></div>
<input type="hidden" name="payment-method-nonce">
<input type="submit" value="Pay">
</form>
<!-- Load the Client component. -->
<script src="https://js.braintreegateway.com/web/3.0.0-beta.8/js/client.min.js"></script>
<!-- Load the Hosted Fields component. -->
<script src="https://js.braintreegateway.com/web/3.0.0-beta.8/js/hosted-fields.min.js"></script>
<script>
var authorization = '{{ $clientToken }}'
braintree.client.create({
authorization: authorization
}, function (clientErr, clientInstance) {
if (clientErr) {
// Handle error in client creation
return;
}
braintree.hostedFields.create({
client: clientInstance,
styles: {
'input': {
'font-size': '14pt'
},
'input.invalid': {
'color': 'red'
},
'input.valid': {
'color': 'green'
}
},
fields: {
number: {
selector: '#card-number',
placeholder: '4111 1111 1111 1111'
},
cvv: {
selector: '#cvv',
placeholder: '123'
},
expirationDate: {
selector: '#expiration-date',
placeholder: '10 / 2019'
}
}
}, function (hostedFieldsErr, hostedFieldsInstance) {
if (hostedFieldsErr) {
// Handle error in Hosted Fields creation
return;
}
form.addEventListener('submit', function (event) {
event.preventDefault();
hostedFieldsInstance.tokenize(function (tokenizeErr, payload) {
if (tokenizeErr) {
// Handle error in Hosted Fields tokenization
return;
}
document.querySelector('input[name="payment-method-nonce"]').value = payload.nonce;
form.submit();
});
}, false);
});
});
</script>
But when I click the submit button, nothing happens.event.preventDefault() stops the submission and the payment_method_nonce token is generated, but I can't submit the form after that, because form.submit() isn't works
How can I submit the form after event.preventDefault()?
Or how can I send the payment_method_nonce token to my controller?
Thanks!
When I copied your snippet and tried to run the example, I got (index):69 Uncaught ReferenceError: form is not defined in the console. When I added
var form = document.getElementById('checkout-form');
it worked just fine.
Best guess, you just forgot to assign the form variable to reference the form dom element. If that's not the case, be sure to let me know.

jQuery dialog partial form submit validation

I have the following partial view (I have removed some of the formatting just to keep it simple on this forum). My form tag is on the parent page, and the items on the dialog are a part of that form.
This is a strongly typed partial view. I have defined the password and confirmPassword fields as [Required] in my Model.
#Html.LabelFor(m => m.password)
Reset Password
<div id="dialogResetPassword" title="Reset Password">
<p>Reset password for user: #Model.userId</p>
#Html.LabelFor(m => m.password)
#Html.PasswordFor(m => m.password)
#Html.ValidationMessageFor(m => m.password)
<div class="rowEnd"></div>
#Html.LabelFor(m => m.confirmPassword)
#Html.PasswordFor(m => m.confirmPassword)
#Html.ValidationMessageFor(m => m.confirmPassword)
<div class="rowEnd"></div>
</div>
I have the following javascript for the initialization of the dialog:
function initializeResetPasswordDialog() {
$(resetPasswordDialogId).dialog(
{
autoOpen: false,
autoResize: true,
buttons: {
Ok: function () {
if (!($('#userForm').valid())) {
return false;
}
//more code goes here ...
closeResetPasswordDialog();
},
Cancel: function () {
closeResetPasswordDialog();
}
}
});
}
My dialog initializes, opens and closes fine, but when I try to check the validity of the items in the dialog, I always get "valid".
I do not want to submit the entire form, but just submit the password and the confirm password fields on the Ok button, and also fire up my validations. Any suggestions on how to do this?
Ok, so I solved it by adding the following function to the open parameter for the jQuery dialog:
open: function () {
$(this).parent().appendTo("#userForm");
}
I noticed that when initializing a jQuery dialog, even though it was within my form, when the HTML page rendered in the browser, the dialog div was moved outside the form. For the validations to work, the inputs must be within a form.
I hope this post helps other people too!

Categories

Resources