Ice_Queen
Ice_Queen

Reputation: 329

SweetAlert2 : Validation required for one of the fields

I am trying to perform validation on one of the fields in the form.

Only if the value for that field exists will I be able to invoke the API, if not an error message will be thrown.

I tried various examples from SweetAlert2's website. I just want the validation for one of the fields.

Swal.fire({
        title: 'Are you sure you want to Save the Notes?',
        type: 'info',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes'
      }).then((result) => {

      console.log('result.value',result.value);
        if (result.value) {
          Swal.fire( {
            title: 'Download Notes',
              html:"<div class='b'><p>ID</p></div><input id='swal-input2' class='swal2-input' required/><div class='b'><p>Notes</p></div><input id='swal-input1' class='swal2-input' autofocus minlength='500' >",
            confirmButtonText: 'Save',
            preConfirm: (login) => {
              console.log('document.getElementById(swal-input2).value',document.getElementById('swal-input2').value);
              request_string = {
        "Request":
          [
            {
              "Col1": "value1",
              "Col1": "value2",
              "Col1": document.getElementById('swal-input2').value,
              "Col1": document.getElementById('swal-input1').value,

            }
          ]
      };
             fetch('API_URL', {
        headers: {
          'Accept': 'application/json, text/plain, application/xml,  */*',
          'Content-Type': 'application/json',
          'Access-Control-Allow-Headers': 'Content-Type',
        },
        method: 'POST',
        body: JSON.stringify(request_string)
      }
      ).then(response => {
        if (response.status !== 200) {

          return;
        }
        response.text().then(data => {

          response_data = data;
          response_jsonObj = JSON.parse(response_data);

        });
      }).catch(error => this.setState({ error }));
  },
  allowOutsideClick: () => !Swal.isLoading()

            }).then((result) => {
              swal({
              title: " Your  request is being processed!",
              icon: "success",
              confirmButtonText: 'OK'
            }).then((okay) => {
              if (okay) {
                history.push('/page1');
                history.push('/page2');
              }
            });
            });
        }
      })

Upvotes: 6

Views: 22425

Answers (4)

Tabraiz Malik
Tabraiz Malik

Reputation: 126

if your using a single input field as text | email | number (In my case Number)

input: 'number'

you could use inputValidator or inputAttributes

inputAttributes: {
     min: 0,
     max: 99999999
},
inputValidator:{
     return 'The input value must be greater than 200';
}

Upvotes: 0

ZakaryaOFC
ZakaryaOFC

Reputation: 39

For those who try to get every inputs with a required attribute try this :

      inputAttributes: {
        input: 'number',
        required: 'true'
      }

Upvotes: 3

Ice_Queen
Ice_Queen

Reputation: 329

Hi folks this as been fixed here is the code sample for the same :

Swal.fire({
        title: 'Are you sure you want to Save the Notes?',
        type: 'info',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes'
      }).then((result) => {

      console.log('result.value',result.value);
        if (result.value) {
          Swal.fire( {
            title: 'Download Notes',
              html:"<div class='b'><p>ID</p></div><input id='swal-input2' class='swal2-input' required/><div class='b'><p>Notes</p></div><input id='swal-input1' class='swal2-input' autofocus minlength='500' >",
            confirmButtonText: 'Save',
            preConfirm: () => {

        if((document.getElementById('swal-input2').value == "") || (document.getElementById('swal-input2').value == '') || ((document.getElementById('swal-input2').value == null)) ){
          Swal.showValidationMessage(
            `ID is a required field`
          )
        }
      }
      }).then((result) => {


      request-string = {
        "Request":
          [
            {
              "COL1": VALUE1,
              "COL2": VALUE2,
              "COL3": VALUE3,
              "COL4": VALUE4,
              "COL5" : VALUE5,
              "COL6" : VALUE6,
              "COL7": VALUE7
            }
          ]
      };
   ;
      fetch('API_URL', {
        headers: {
          'Accept': 'application/json, text/plain, application/xml,  */*',
          'Content-Type': 'application/json',
          'Access-Control-Allow-Headers': 'Content-Type',
        },
        method: 'POST',
        body: JSON.stringify(request-string)
      }
      ).then(response => {
        if (response.status !== 200) {

          return;
        }
        response.text().then(data => {

          response_data = data;
          response_jsonObj = JSON.parse(response_data);
          this.setState({ state: response_jsonObj });

        });
      }).catch(error => this.setState({ error }));

      swal({
        title: "Request Submitted Successfully!",
        icon: "success",
        confirmButtonText: 'OK'
      }).then((okay) => {
        if (okay) {
          history.push('/page1');
          history.push('/page2');
        }
      });
      });

Upvotes: 0

G. Verni
G. Verni

Reputation: 707

If you just want to make sure that the first input (i.e. swal-input2) is not null, then you simply need to add preConfirm like that:

    preConfirm: () => {
      if (document.getElementById('swal-input2').value) {
         // Handle return value 
      } else {
        Swal.showValidationMessage('First input missing')   
      }
    }

You can find the working solution here

Upvotes: 15

Related Questions