SweetAlert input validation - javascript

I want the alert to not disappear when the user is trying to submit an empty form,instead it should show some error in the same alert.I tried doing swal.showInputError("some error") but it gives an error that it is not
valid function.I tried looking at the documentation but cannot find any...
Here is my code-
swal({
title:"Enter a Username",
content: {
element: "input",
attributes: {
placeholder: "Type your username",
type: "text"
},
},
className: "mySwal"
}).then((username)=>{
//get the username
if(username){
}else{
}
});

You can use this function:
inputValidator: (value) => {
return !value && 'You need to write something!'
}
This will validates if the user is writing a value.

This will also Work
showCancelButton: true,
preConfirm: (value) => {
if (!value) {
Swal.showValidationMessage(
'You need to write something!'
)
}
}

This works to me
inputValidator: (value) => {
if (!value) return 'Your text here'
else return null
}

Related

Is there a way to add a cancel button with an input field in Sweetalert, Reactjs

I'm trying to create an Swal alert that must contain an input field with a continue and cancel button in ReactJs. This is my code right now:
swal({
icon: "warning",
text: 'Are you sure you want to continue? This operation is not reversible',
content: {
element: "input",
attributes: {
placeholder: title + " reason",
},
},
}).then(comment => {
if (comment === null || comment === ''){
swal({icon: 'error', text: 'You need to type the cancellation reason'});
return false
}
})
This code only creates an 'OK' button and I get the input from the user in the comment variable, but I need to add a 'Continue' button and a 'Cancel' button to leave the alert. I've tried adding the button parameter in the swal options and this creates the buttons but I'm not able to get the input from the user.
I also have tried to add raw html in the content and get the input with a handle method but so far I haven't been able to do this.
Maybe the solution for this is easy but I am not able to get it. Thank a lot for the help
I found out a way to solve this in case anyone have to do something similar. I just created the input by doing document.createElement('input') and then I got the value depending on the user clicked on Continue or Cancel:
const cancellation_reason = document.createElement('input');
swal({
icon: "warning",
text: 'Are you sure you want to continue? This operation is not reversible',
content: {
element: cancellation_input,
attributes: {
placeholder: title + " reason",
},
},
buttons: {
continue: 'continue',
cancel: 'cancel'
}
}).then(option => {
switch (option){
case 'continue':
if (cancellation_input.value === null || cancellation_input.value === ''){
swal({icon: 'error', text: 'You need to type the cancellation reason'});
return false
}
prop(runID, null, path, cancellation_input.value).then(showMesagge);
break;
case 'cancel':
break;
}
})

Use dangerMode and input in same time - sweetalert

I using Sweet Alert, so before perform a dangerous action I popup the dialog box. Example.
swal({
title: "Are you sure?",
text: "Once deleted, you will not be able to recover this imaginary file!",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
swal("Poof! Your imaginary file has been deleted!", {
icon: "success",
});
} else {
swal("Your imaginary file is safe!");
}
});
But user can enter any remarks if they want, is optional and not required. So it will become like this
So I modified the code like this
function RequestUpload(value) {
swal({
title: "Are you sure?",
text: "Are you sure want to request to upload?",
icon: "warning",
buttons: true,
dangerMode: true,
content: {
element: "input",
attributes: {
placeholder: "Any remarks?",
type: "text",
},
},
})
.then((willDelete,input) => {
if (willDelete) {
swal(`You typed: ${input}`);
//Call ajax here
}
else {
swal(`Is not delete`);
}
});
}
But I can't get the value from the input, it keep show undefined.
Any idea how to fix this?
The input value is provided as the first argument. When you click cancel, click outside of the popup or press ESC, you'll get null for the value which will close the alert (ie: trigger your else). Otherwise, if you click "Ok" it will hold your input value:
.then((input) => {
if (input !== null) {
swal(`You typed: ${input}`);
//Call ajax here
} else {
swal(`Is not delete`);
}
});
function RequestUpload(value) {
swal({
title: "Are you sure?",
text: "Are you sure want to request to upload?",
icon: "warning",
buttons: true,
dangerMode: true,
content: {
element: "input",
attributes: {
placeholder: "Any remarks?",
type: "text",
},
},
})
.then((input) => {
if (input !== null) {
swal(`You typed: ${input}`);
//Call ajax here
} else {
swal(`Is not delete`);
}
});
}
RequestUpload();
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>

Using sweet alert instead of custom js confirms, but ending with errors

I am trying to use sweetalert.js instead of custom JS confirms. I was modifiying following code..
clear.addEventListener("click", (e) => {
if(confirm("Warning, this action will remove all the text data as well as your saved starting
and ending time")){
localStorage.removeItem('startTime');
localStorage.removeItem('endTime');
window.location.reload();
} else {
e.preventDefault();
}
})
})
code I replaced with
function clearConfirm(message){
var t=false;
swal({
title: "Are you sure?",
text: message,
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
swal("file has been deleted!", {
icon: "success",});
t=true;
} else {
swal("Your data is safe!");
t=false;
}
});
if(t==true){
swal("Your file is safe!");
return true;
}else{
return false;
}
}
clear.addEventListener("click", (e) => {
if(clearConfirm("all the data will get removed")==true){
localStorage.removeItem('startTime');
localStorage.removeItem('endTime');
window.location.reload();
} else {
e.preventDefault();
}
})
As custom js returns value 'true' upon pressing 'OK' button and 'false' upon 'Cancel' button, so I tried to put the sweetalert confirm in a function and then return a true or false in above 'if' statement
.....But when I run it the function gets executed but it doesn't return value and the if condition doesnt move forward...it just pops up the confirm and after pressing OK button the desired action isn't completed(here i want to clear some data in a page)...
Please help through it.
You have return Promise from your clearConfirm function and use as shown below
function clearConfirm(message) {
return swal({
title: "Are you sure?",
text: message,
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
swal("file has been deleted!", {
icon: "success",
});
return true;
} else {
swal("Your data is safe!");
return false;
}
});
}
clear.addEventListener("click", (e) => {
clearConfirm("all the data will get removed").then((deleted) => {
if (deleted) {
localStorage.removeItem('startTime');
localStorage.removeItem('endTime');
window.location.reload();
} else {
e.preventDefault();
}
})
})

How to make Vue's element-ui validateField() works with v-if?

Please look at password fields. Password and Confirm Password fields shows when Change Password? button is clicked.
Below code works fine and validates the form as expected with v-show but does not validates when v-if is used.
I understand what v-show and v-if does, and the functions in data(){} that's how it's in element-ui's doc. Here is the doc's url: http://element.eleme.io/#/en-US/component/form#custom-validation-rules
<template lang="pug">
el-dialog( width="600px", title="Users", :visible.sync="dialogVisible")
el-form.demo-ruleForm(:model="editedItem", status-icon, :rules="formRules", ref="userForm", label-width="140px")
el-form-item(label="Name", prop="firstName")
el-input(v-model="editedItem.name", auto-complete="off")
template(v-if="!changePassword")
el-form-item
el-button(#click="changePassword = true") Change Password?
template(v-else)
el-form-item(label="Password", prop="password")
el-input(type="password", v-model="editedItem.password", auto-complete="off")
el-form-item(label="Confirm Password", prop="confirmPassword")
el-input(type="password", v-model="editedItem.confirmPassword", auto-complete="off")
.dialog-footer(slot="footer")
el-button(type="primary", #click="submitForm('userForm')") Save
</template>
<script>
export default {
name: 'dialog-add-edit-user',
props: {
editedItem: Object,
},
data () {
const validatePass = (rule, value, callback) => {
if (value === '') {
callback(new Error('Please input the password'))
} else {
if (this.confirmPassword !== '') {
this.$refs.userForm.validateField('confirmPassword')
}
callback()
}
}
const validatePass2 = (rule, value, callback) => {
if (value === '') {
callback(new Error('Please input the password again'))
} else if (value !== this.editedItem.password) {
callback(new Error('Two inputs don\'t match!'))
} else {
callback()
}
}
return {
formRules: {
password: [
{
validator: validatePass,
trigger: 'blur'
}
],
confirmPassword: [
{
validator: validatePass2,
trigger: 'blur'
}
]
},
dialogVisible: false,
changePassword: false,
editedItem: {
name: '',
password: '',
confirmPassword: ''
}
}
},
methods: {
submitForm (formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
this.$emit('save-item')
console.log('submit!')
} else {
console.log('error submit!!')
return false
}
})
}
}
}
</script>
Ok, I think I understand what the issue is.
your validation is passing, but it's not checking name and password, only passwordChange.
so if you "... understand what v-show and v-if does" you'll know that the elements do not exist when you use v-if/v-else. They get added and removed as needed.
The reason this is a problem is that the element library goes through a initialization stage when they get added. The element gets referenced later using $ref. look at SubmitForm, it uses `this.$refs[formName].validate'
so when you use v-if/v-else, because the elements were not there to begin with, they will not be called properly.
you have two options, either stick with v-show, which should be easy enough, or you can use a hack I've been exploiting with 3rd party libraries that don't allow forcing a manual or auto reload. The hack consists of adding a key to the main element. So the html would look like this.
<el-form
class="demo-ruleForm"
:model="editedItem"
status-icon="status-icon"
:key="'form'+changePassword" <--- this is the magic
:rules="formRules"
ref="userForm"
label-width="140px"
>
and in pug
el-form.demo-ruleForm(:model="editedItem", :key="'form'+changePassword", status-icon, :rules="formRules", ref="userForm", label-width="140px")

Dojo Programmatically validate TextBox

I'm trying to create a dojo form programmatically and validate input TextBox on button click. But when I try to valid I get an error "dijit.byId(..) is undefined. Below is the code:
var form = new dijit.form.Form({
nametb: new dijit.form.TextBox({
name: "name",
type: "text",
required: true,
placeHolder: "Your Full Name"
},"nametb"),
subBtn: new dijit.form.Button({
label: "Proceed",
onClick: function(){
if(dijit.byId("nametb").get('value') == null || dijit.byId("nametb").get('value').length == 0 )
{
alert("Please enter Name");
return false;
}
}
}),
cnclBtn: new dijit.form.Button({
label: "Cancel",
onClick: function(){
dia.hide();
}
}),
postCreate: function(){
this.domNode.appendChild(this.nametb.domNode);
this.domNode.appendChild(this.subBtn.domNode);
this.domNode.appendChild(this.cnclBtn.domNode);
}
});
But now when I click the Proceed button I get an error dijit.byId(...) is undefined
How can I validate this TextBox?
You never set an id for nametb, so dijit.byId() isn't able to find the textbox and throws an error. Try
nametb: new dijit.form.TextBox({
name: "name",
type: "text",
id: "nametb",
Just try with this on specified widget :
// validate nametb textbox
dijit.byId("nametb").validate();
Or you can validate the form like this:
if (dijit.byId("yourForm").validate()) {
// do something if your form is valid
} else {
// show error message
}

Categories