admin管理员组

文章数量:1293455

This code works perfectly in HTML

<input type="text" name="country" pattern="[A-z]{3}"
    oninput="if (typeof this.reportValidity === 'function') {this.reportValidity();}"/>

How do I use it in Svelte. oninput is not allowed. I tried on:input, but I don't have access to this

This code works perfectly in HTML

<input type="text" name="country" pattern="[A-z]{3}"
    oninput="if (typeof this.reportValidity === 'function') {this.reportValidity();}"/>

How do I use it in Svelte. oninput is not allowed. I tried on:input, but I don't have access to this

Share Improve this question asked Feb 12 at 17:08 ZAkyZAky 1,3099 silver badges25 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

You need to pass in a function via { ... }, e.g.

<input type="text" name="country" pattern="[A-z]{3}"
    oninput={function() { this.reportValidity(); }} />

this is just the element, you can also get that from the event object, e.g.

<input type="text" name="country" pattern="[A-z]{3}"
    oninput={e => e.target.reportValidity()} />

Using the event object is more common, it is also helpful for event delegation (the target can be a descendant from which the event originated).

See:

  • target
  • currentTarget (always the element the handler was set on)

For longer or reused functions, it is recommended to put them in the <script> and reference them.

<script>
  function validateCountry(e) {
    e.target.reportValidity();
  }
</script>
<input type="text" name="country-a" pattern="[A-z]{3}"
    oninput={validateCountry} />
<input type="text" name="country-b" pattern="[A-z]{3}"
    oninput={validateCountry} />

本文标签: How do I use oninput thisreportValidity in svelteStack Overflow