Skip to content

Instantly share code, notes, and snippets.

@kimprosh
Created August 5, 2019 02:06
Show Gist options
  • Save kimprosh/08fdad56cf6840c6ec51237f53d5bba9 to your computer and use it in GitHub Desktop.
Save kimprosh/08fdad56cf6840c6ec51237f53d5bba9 to your computer and use it in GitHub Desktop.
SweetAlert AJAX form validation example
<div id="form-template" class="hidden">
<form>
<div class="row">
<div class="col-sm-12">
<input name="username" placeholder="Username" class="swal-content__input" type="text">
</div>
</div>
<div class="row">
<div class="col-sm-12">
<input name="password" placeholder="Password" class="swal-content__input" type="password">
</div>
</div>
</form>
</div>
<div class="row center-sm">
<div class="col-sm-12">
<p><button id="click-me-btn">Click me</button></p>
</div>
</div>
// store form HTML markup in a JS variable
var formTemplate = $('#form-template > form').clone()[0];
$('#form-template').remove();
// prepare SweetAlert configuration
var swalConfig = {
title: 'Demo Form',
content: formTemplate,
button: {
text: 'Submit',
closeModal: false
}
};
// handle clicks on the "Click me" button
$('#click-me-btn').click(function () {
swal(swalConfig);
});
// handle clicks on the "Submit" button of the modal form
$('body').on('click', '.swal-button--confirm', function() {
simulateAjaxRequest();
});
// mock AJAX requests for this demo
var isFakeAjaxRequestSuccessfull = false;
function simulateAjaxRequest() {
// "send" the fake AJAX request
var fakeAjaxRequest = new Promise(function (resolve, reject) {
setTimeout(function () {
isFakeAjaxRequestSuccessfull ? resolve() : reject();
isFakeAjaxRequestSuccessfull = !isFakeAjaxRequestSuccessfull;
swal.stopLoading();
}, 200);
});
// attach success and error handlers to the fake AJAX request
fakeAjaxRequest.then(function () {
// do this if the AJAX request is successfull:
$('input.invalid').removeClass('invalid');
$('.invalid-feedback').remove();
}).catch(function () {
// do this if the AJAX request fails:
var errors = {
username: 'Username is invalid',
password: 'Password is invalid'
};
$.each(errors, function(key, value) {
$('input[name="' + key + '"]').addClass('invalid').after('<div class="invalid-feedback">' + value + '</div>');
});
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert@2.0.8/dist/sweetalert.min.js"></script>
.hidden {
display: none;
}
form > .row {
margin-bottom: 20px;
}
form > .row:last-child {
margin-bottom: 0;
}
form input.invalid {
border-color: #dc3545;
}
form .invalid-feedback {
color: #dc3545;
font-size: 14px;
line-height: 21px;
margin-top: 4px;
text-align: left;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/flexboxgrid/6.3.1/flexboxgrid.min.css" rel="stylesheet" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment