Created
July 31, 2018 10:17
-
-
Save Werninator/289bff1a6c96b96e969dc8e64f031fd6 to your computer and use it in GitHub Desktop.
sweetalert2 login box
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// it's in german but you can translate it if you want to | |
import swal from "sweetalert2"; | |
import axios from "axios"; | |
const loginPopup = () => { | |
swal({ | |
title: "Login", | |
backdrop: false, | |
showCancelButton: true, | |
confirmButtonText: "Login", | |
cancelButtonText: "Abbrechen", | |
html: | |
'<label for="username">Nutzername</label>\ | |
<input type="text" name="username" id="username" class="swal2-input" />\ | |
<label for="password">Passwort</label>\ | |
<input type="password" name="password" id="password" class="swal2-input" />', | |
onOpen: () => { | |
const confirmOnEnter = e => | |
e.keyCode == 13 && | |
document | |
.querySelector(".swal2-actions > .swal2-confirm") | |
.click(); | |
document.getElementById("username").focus(); | |
document | |
.getElementById("username") | |
.addEventListener("keyup", confirmOnEnter); | |
document | |
.getElementById("password") | |
.addEventListener("keyup", confirmOnEnter); | |
}, | |
preConfirm: () => { | |
const retVal = [ | |
document.getElementById("username").value, | |
document.getElementById("password").value | |
]; | |
const [username, password] = retVal; | |
if (!username.trim()) | |
swal.showValidationError("Nutzername wurde nicht ausgefüllt"); | |
else if (!password.trim()) | |
swal.showValidationError("Passwort wurde nicht ausgefüllt"); | |
return retVal; | |
} | |
}).then(result => { | |
if ("dismiss" in result) return; | |
const [username, password] = result.value; | |
swal({ | |
title: "Lade..", | |
backdrop: false, | |
allowEscapeKey: false, | |
onOpen: () => { | |
swal.showLoading(); | |
axios | |
.post("/login", { | |
username, | |
password | |
}) | |
.then(response => { | |
swal.close(); | |
if (response.data.loggedIn) { | |
swal({ | |
title: "Login erfolgreich!", | |
text: "Die Seite wird in Kürze neu geladen..", | |
type: "success", | |
backdrop: false | |
}); | |
} else { | |
swal({ | |
title: "Login fehlgeschlagen!", | |
type: "error", | |
backdrop: false, | |
showCancelButton: true, | |
confirmButtonText: "Erneut versuchen", | |
cancelButtonText: "Abbrechen" | |
}).then(result => { | |
if (result.value) loginPopup(); | |
}); | |
} | |
}); | |
} | |
}); | |
}); | |
}; | |
export default loginPopup; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment