js限制文本框只能输入整数或者带小数点的数字
作者:hebedich 时间:2024-04-18 09:46:02
做表单验证的时候是否会碰到验证某个输入框内只能填写数字呢,仅允许输入整数数字或者带小数点的数字。下面这段代码也许能帮到你!通过对当前输入框定义onkeypress,onkeyup,onblur事件对表单做了充分的验证,结果还是非常靠谱的。
<input type="text" value="" t_value="" o_value="" onkeypress="if(!this.value.match(/^[\+\-]?\d*?\.?\d*?$/))this.value=this.t_value;else this.t_value=this.value;if(this.value.match(/^(?:[\+\-]?\d+(?:\.\d+)?)?$/))this.o_value=this.value" onkeyup="if(!this.value.match(/^[\+\-]?\d*?\.?\d*?$/))this.value=this.t_value;else this.t_value=this.value;if(this.value.match(/^(?:[\+\-]?\d+(?:\.\d+)?)?$/))this.o_value=this.value" onblur="if(!this.value.match(/^(?:[\+\-]?\d+(?:\.\d+)?|\.\d*?)?$/))this.value=this.o_value;else{if(this.value.match(/^\.\d+$/))this.value=0+this.value;if(this.value.match(/^\.$/))this.value=0;this.o_value=this.value}" />
下面对onkeypress,onkeyup,onblur事件做简要的解释。
onkeypress 事件会在键盘按键被按下并释放一个键时发生。
onkeyup 事件会在键盘按键被松开时发生。
onblur 事件会在对象失去焦点时发生。
另外需要注意的是如果需要做严格验证的表单,一定要客户端和服务器端进行双重验证,以上紧紧做了客户端验证。如果稍微懂点程序的人,能够很轻松的绕过这段验证代码,如果服务器端没有进行验证的话,就很容易出问题的。
以上所述就是本文的全部内容了,希望大家能够喜欢。
标签:js,整数,小数
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
php导出excel格式数据问题
2023-07-13 22:46:06
python 算法 排序实现快速排序
2022-09-04 03:20:17
深入解析Python编程中JSON模块的使用
2022-11-30 00:21:27
在JavaScript中调用Java类和接口的方法
2024-04-10 10:42:49
Python编程中NotImplementedError的使用方法
2023-06-08 15:40:40
Python splitlines使用技巧
2023-01-11 01:13:56
python爬取豆瓣电影TOP250数据
2021-12-27 12:50:17
![](https://img.aspxhome.com/file/2023/9/95199_0s.png)
js实现根据文件url批量压缩下载成zip包
2024-04-22 22:15:17
![](https://img.aspxhome.com/file/2023/0/136060_0s.png)
Python处理PPT文件的实用知识点总结
2021-04-26 04:11:10
golang:json 反序列化的[]和nil操作
2024-04-26 17:19:24
详解Vue.use自定义自己的全局组件
2024-05-02 17:02:59
![](https://img.aspxhome.com/file/2023/6/130076_0s.png)
使用python将最新的测试报告以附件的形式发到指定邮箱
2022-08-24 14:59:16
![](https://img.aspxhome.com/file/2023/5/96925_0s.png)
python实现剪切功能
2023-02-27 17:52:01
![](https://img.aspxhome.com/file/2023/4/109864_0s.jpg)
画pytorch模型图,以及参数计算的方法
2023-09-25 09:12:58
![](https://img.aspxhome.com/file/2023/1/133901_0s.jpg)
Mysql中where与on的区别及何时使用详析
2024-01-21 03:31:19
![](https://img.aspxhome.com/file/2023/3/65293_0s.png)
JS添加删除一组文本框并对输入信息加以验证判断其正确性
2024-05-03 15:30:54
scrapy-splash简单使用详解
2023-06-02 15:22:37
![](https://img.aspxhome.com/file/2023/1/103161_0s.jpg)
Pytest测试框架基本使用方法详解
2022-06-23 20:49:04
vs code开发中语法正确但显示报错问题分析解决
2023-08-05 11:54:26
![](https://img.aspxhome.com/file/2023/7/132427_0s.png)
精简化的产品设计
2008-07-26 12:22:00