colinaut / alpinejs-plugin-simple-validate

Simple Alpine form validation plugin
97 stars 4 forks source link

How can I set the validation to true or false for a specific field? #18

Closed QJan84 closed 11 months ago

QJan84 commented 1 year ago

How can I set the validation to true or false for a specific field?

On input, checkIBAN() checks the IBAN with an API and returns true/false to me.

How can I give the field "sepa_iban" now true or false?

Kinda like this: this.$validate.data('sepa_iban' == false)

        <div class="space-y-1">
          <label for="sepa_iban" class="label-input">IBAN <span class="form-required">*</span></label>
          <input type="text" class="form-input" id="sepa_iban" x-ref="sepa_iban" name="SEPA[SEPA_IBAN]" x-model="sepa_iban" required data-error-msg="Bitte geben Sie Ihre IBAN ein." @input.debounce="checkIBAN('DE34532453245235235')">
        </div>
QJan84 commented 1 year ago

Not perfect, but it works.

<input type="text" class="form-input" id="sepa_iban" name="SEPA[SEPA_IBAN]" x-model="sepa_iban" required x-validate data-error-msg="Bitte geben Sie Ihre korrekte IBAN ein." @input.debounce="checkIBAN()">

      checkIBAN(iban){
        var myHeaders = new Headers();
        myHeaders.append("apikey", "YOUR_KEY");
        var requestOptions = {
          method: 'GET',
          redirect: 'follow',
          headers: myHeaders
        };
        fetch(`https://api.apilayer.com/bank_data/iban_validate?iban_number=${this.sepa_iban}`, requestOptions)
          .then(response => response.json())
          .then(result => {
            if(!result.valid){

              // This works for now
              this.$validate.data('sepa_iban').valid = false;
              this.$validate.toggleError('sepa_iban',false);

            }
          })
          .catch(error => console.log('error', error));
      }
colinaut commented 11 months ago

Yeah this works. You could also possibly add the content to the field via the DOM and then trigger a focus/blur. Both are kinda kludgy but I didn't really plan for this usage. I'm thinking of rewriting this plugin to use a mutation observer on the value which would solve this but I need to test that and see what the JS load is vs the simple focus event.

I'm going to close this for now since you have a solution.