如何在Svelte中使用on:input调用reportValidity方法?
在Svelte中实现实时输入验证功能
你可以通过两种方式实现和这段HTML相同的功能:
方法一:利用事件对象的currentTarget
在Svelte的on:input事件回调里,通过event.currentTarget就能获取到触发事件的输入框元素,替代HTML里的this:
<input type="text" name="country" pattern="[A-z]{3}" on:input={(event) => { const input = event.currentTarget; if (typeof input.reportValidity === 'function') { input.reportValidity(); } }} />
方法二:绑定元素引用
如果需要在其他逻辑里也操作这个输入框,可以用bind:this把元素挂载到变量上:
<script> let countryInput; </script> <input type="text" name="country" pattern="[A-z]{3}" bind:this={countryInput} on:input={() => { if (countryInput && typeof countryInput.reportValidity === 'function') { countryInput.reportValidity(); } }} />
两种方式都能实现输入时实时验证并弹出浏览器默认提示框的效果,和你原来的HTML代码功能完全一致。
内容的提问来源于stack exchange,提问作者ZAky
相关产品推荐
相关产品推荐

