使用JavaScript验证文本框值 [英] Validating a text box value using javascript

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

问题描述

我有一个文本框.用户将在此框中输入数字.用户应输入两个数字,后跟一个句点.".和另一个数字.看起来像是22.3或00.5或11.2.

I have a textbox.The user will be entering entering a number in this box.The user should enter two digits followed by a period "." and another digit.It would look something like 22.3 or 00.5 or 01.2.

如果文本框不为空,我想执行一个功能来验证用户输入的值(如果输入的值不符合上述格式,则向他们发出警报).此功能需要触发当文本框失去焦点时,我不确定如何继续编写此函数,因为我对此还很陌生.任何帮助,我们将不胜感激.

If the textbox is not empty,I want to enforce a function which validates the value entered by the user(and gives them an alert if the value entered is not according to the format mentioned above) .This function needs to be triggered when the textbox loses its focus.I am not sure how to go ahead in writing this function as i am still new to this. Any help would be appreciated.Thanks in advance.

ps该函数应在每次值更改时触发.例如,假设用户输入一个值22,然后当文本框失去焦点时,应触发javascript函数,向他们发出警告,询问用户将其更改为可接受的格式,即22.0.当文本框失去焦点(更改完成后)时,应再次触发该功能.由于用户以正确的格式输入了该时间,因此不会出现警报.

p.s This function should be triggered each time there is a change in the value.Like suppose, the user enters a value 22, then when the textbox loses its focus,the javascript function should be triggered giving them an alert asking the user to change it to the accepted format which is 22.0.The function should be triggered again when the textbox loses its focus(after the change has been done).This time there would not be an alert since the user entered it in the right format.

推荐答案

请原谅特定于Prototype的代码,但也许您会领会到它的要旨.您将需要侦听textarea的"onblur"事件,然后使用正则表达式验证输入的值.

Excuse the Prototype specific code, but maybe you'll get the gist of it. You'll want to listen on the "onblur" event of the textarea, and then validate the entered value with a regular expression.

Event.observe('textboxId', blur, function() {
  var val = $F('textboxId');
  if (/^\d{2}\.\d$/.test(val)) {
    alert('Invalid value');
  }
});

如果您不熟悉任何javascript框架,只是想使它正常工作,请尝试以下操作:

If you're not familiar with any javascript frameworks, and just want to get this working, try this:

<textarea onblur="validate(this.value);"></textarea>

<script type="text/javascript">
function validate(val) {
  if (/^\d{2}\.\d$/.test(val)) {
    alert('Invalid value');
  }
}
</script>

纯粹主义者,请不要因为添加了这个而惩罚我.

Purists, please don't punish me for adding this.

这篇关于使用JavaScript验证文本框值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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