Search code examples
javascriptformssweetalert2

Sweetalert - validation isn't working + form is not submitting


I am trying to implement sweetalert2 but for some reason it doesn't apply regular html validation (i.e. required='true' isn't working), I am not getting an error that the field is empty.

Without swall2, it does prompt me with an error that the field is blank.

Also, once I confirm, in the swall dialog, that I want to proceed ("Yes, submit it!"), it does not submit the form.

What am I missing?

JSfiddle

HTML:

<form>
   <label>Last Name</label>
   <input type="text"  required="true"/>
   <input class="btnn" type="submit" name="submit" id="btn-submit"/>
</form>

Javascript:

$('#btn-submit').on('click', function(e) {
    e.preventDefault();
    var form = $('form');
    swal.fire({
        title: "Are you sure?",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Yes, submit it!",
        closeOnConfirm: false
    }, function(isConfirm) {
        if (isConfirm) form.submit();
    });
});

Solution

  • The documentation says after it has migrated to sweetalert2 the structure has changed from callback approach

    swal(
          {title: 'Are you sure?', showCancelButton: true}, function(isConfirm) {
          if (isConfirm) {
          // handle confirm
          } else {
          // handle all other cases
        }
      }
    )
    

    to promise based approach

    Swal.fire({title: 'Are you sure?', showCancelButton: true}).then(result => {
     if (result.value) {
      // handle Confirm button click
     // result.value will contain `true` or the input value
     } else {
       // handle dismissals
       // result.dismiss can be 'cancel', 'overlay', 'esc' or 'timer'
     }
    })