在输入时验证 html 文本输入 [英] Validate html text input as it's typed

查看:35
本文介绍了在输入时验证 html 文本输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在输入时验证 HTML 文本输入的最佳方法是什么?我所知道的所有方法都有一些缺点:

What's the best way of validating an HTML text input as it's typed? All ways I know of doing it has some drawbacks:

  1. 使用 $.keypress 您只能访问输入的旧值,而不能访问新值.此外,某些事件(如使用鼠标剪切/粘贴)将不会被检测到.

  1. Using $.keypress you only have access to the input's old value, not the new one. Also, some events (like cutting/pasting using the mouse) won't be detected.

使用 $.change 仅在输入失去焦点时有效.

Using $.change only works when the input loses focus.

这个问题提出了一个解决方案,您可以使用轮询来观察属性变化.原则上,可以在回调中验证新值,如果无效则返回旧值.但是,除了需要轮询之外,我不确定它是否没有竞争条件.

This question proposes a solution, where you use polling to watch for property changes. In principle, it's possible to validate the new value in the callback, then revert to the old one if invalid. However, besides requiring polling, I'm not sure it's free from race conditions.

这篇文章建议在存在时使用浏览器特定功能,如果没有可用,则回退到轮询.目前看来是最好的方法.

This article suggests using browser specific features when present, falling back to polling if none is available. Looks like the best approach so far.

[Update] 正如答案中所指出的,$.keyup 允许在更新后访问该值.但是,它不仅不适用于鼠标剪切/粘贴,而且如果您按住某个键也会失败,只有在输入很多后才能释放.或者,如果结合 keydownkeyup 来保存/恢复旧值,如果用户输入太快就会中断.

[Update] as pointed in the answers, $.keyup give access to the value after update. However, not only it doesn't work for mouse cut/paste, but also fails if you press and hold a key, only releasing after a lot has been entered. Or, if combining keydown and keyup to save/restore the old value, it breaks if the user types too fast.

以上解决方案都没有错误或真正安全的跨浏览器.是否有更好的解决方案,无论是现成的还是正在制定的?似乎是一个常见问题,我试图回答类似 问题 最近,没有成功,我也对答案很感兴趣.

None of the solutions above are error free or really safe cross-browsers. Are there better solutions out there, either ready-to-use or in-the-making? Seems to be a common problem, I've attempted to answer similar questions recently, with no success, and I'm interested in an answer as well.

(一个很好的论据反对这种做法也是受欢迎的,以防如果实施这种验证会出现新问题;但是,这在其他语言中似乎很常见,所以我怀疑想要是一件坏事)

(A good argument against this practice is also welcome, in case there are new problems that would rise if this validation were implemented; however, that seems a common thing in other languages, so I doubt it is a bad thing to want)

推荐答案

您可以使用 input (FF) 和 propertychange(所有其他)事件来捕获所有表单输入包括键盘和人民币剪切粘贴.

You can use the input (FF) and propertychange (all others) events to catch all forms of input including keyboard and rmb cut paste.

http://jsfiddle.net/dFBzW/

$('input').bind('input propertychange', function() {
    $('#output').html($(this).val());
});

这篇关于在输入时验证 html 文本输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆