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

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

问题描述

在键入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.

使用 $。更改仅在输入失去焦点时才有效。

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.

[更新] ,如答案所示, $。 keyup 在更新后授予对值的访问权限。但是,它不仅不适用于鼠标剪切/粘贴,而且如果按住某个键也会失败,只有在输入很多内容后才会释放。或者,如果组合 keydown keyup 来保存/恢复旧值,则如果用户键入太快则会中断。

[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)

推荐答案

您可以使用输入(FF)和 propertychange (所有其他)事件,以捕获所有形式的输入,包括键盘和rmb剪切粘贴。

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天全站免登陆