js正则表达式,限1-2位整数,或者至多含有两位小数

本文介绍了一种使用正则表达式验证特定格式数字的方法,包括整数和最多包含两位小数的浮点数。通过具体示例展示了如何判断字符串是否符合预期的数字格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. $(function(){    
  2.       
  3.     //1、只能输入数字或者小数点    仅整数,整数加小数  
  4.     var reg1=/(^[0-9]{1,2}$)|(^[0-9]{1,2}[\.]{1}[0-9]{1,2}$)/;  
  5.     console.log(reg1.test("")+" 空串 false");  
  6.     console.log(reg1.test("1")+" 1 true");  
  7.     console.log(reg1.test("10")+" 10 true");  
  8.     console.log(reg1.test("10.")+" 10. false");  
  9.     console.log(reg1.test("100")+" 100 false");  
  10.     console.log(reg1.test("100.1")+" 100.1 false");  
  11.     console.log(reg1.test("10.1")+" 10.1 ture");  
  12.     console.log(reg1.test("10.10")+" 10.10 true");  
  13.     console.log(reg1.test("10.101")+" 10.101 false");  
  14.     console.log(reg1.test("0.101")+" 0,101 false");  
  15.     console.log(reg1.test("110.101")+" 110.101 false");  
  16.     console.log(reg1.test("a")+" a false");  
  17.     console.log(reg1.test("*")+" * false");  
  18.     console.log(reg1.test("..")+" .. false");  
  19.       
  20.       
  21. })  
### 使用 `el-input` 和正则表达式实现两位小数验证 为了确保 `el-input` 组件中的输入只允许两位小数,可以通过组合使用 Vue.js 的事件处理机制和 JavaScript正则表达式来完成这一需求。下面是一个完整的解决方案: #### HTML 部分 ```html <template> <div> <el-input v-model="inputValue" @input="handleInput"></el-input> </div> </template> ``` #### Script 部分 ```javascript <script> export default { data() { return { inputValue: '' }; }, methods: { handleInput(value) { // 移除非数字字符以及多余的点号 let newValue = value.replace(/[^0-9.]/g, ''); // 如果有多个点,则仅保留第一个点 newValue = newValue.replace(/\.{2,}/g, '.').replace(/^\.|\.$/g, ''); // 应用正则表达式制最多两个整数两位小数 const regex = /^(?!0\d)\d{0,2}(\.\d{0,2})?$/; if (newValue.match(regex)) { this.inputValue = newValue; } else { // 若不符合规则,则恢复之前的值 this.inputValue = this.inputValue.slice(0, -1); } } } }; </script> ``` 此方法首先移除了所有非数字字符(包括字母和其他符号),并确保只有一个有效的小数点存在。接着应用了一个更严格的正则表达式 `/^(?!0\d)\d{0,2}(\.\d{0,2})?$/` 来进一步过滤输入,使得最终的结果满足不超过两位整数部分且至多含有两位小数的要求。 该方案不仅实现了对输入内容的有效控制,还能够防止用户输入非法数据,从而提高了用户体验的质量[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值