Search code examples
javascriptjquerysweetalertsweetalert2

Sweet Alert custom regex validation with proper message


I am using SweetAlert2 in my project. I am populating a text field inside my sweet alert input type text. I need to check it with any regex before submit and if it is successful, it should run the function otherwise it should display an error message.

swal({
    title: 'Edit Breakdown Variable',
    input: 'text',
    inputValue: name,
    showCancelButton: true,
    confirmButtonText: 'Update',
}).then(function (email) {
    if(email == ''){
        alert('err');
    }
});

If there is error, alert is displayed but the popup disappears after it. Has anyone encountered such an issue before?


Solution

  • Check below example if it helps you.

    swal({
        title: 'Edit Breakdown Variable',
        input: 'text',
        showCancelButton: true,
        confirmButtonText: 'Update',
        preConfirm: function (email) {
            return new Promise(function (resolve, reject) {
                setTimeout(function () {
                    if (email === '') {
                        alert("err");
                        reject('err')
                    } else {
                        resolve()
                    }
                }, 1000)
            })
        },
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.3.4/bluebird.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.11.0/sweetalert2.min.css" rel="stylesheet"/>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.11.0/sweetalert2.min.js"></script>