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
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} />