You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 11:52:02