只能输入数字和小数点的正则

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form action="" novalidate> 
  <input type="text" autocomplete="off" id="price" autofocus="autofocus" oninput="value=value.replace(/[^\d^\.]+/g,'')" onkeyup="value=value.replace(/[^\d^\.]+/g,'')"> 
</form>
</body>
</html>
注意:这里必须加上input。不然会导致最后一个keyup如果输入的为字符,会保存下来

以上代码其实不能保证只输入一个小数点,要想只输入一个小数点必须加上

replace('.','$#$').replace(/\./g,'').replace('$#$','.')  // 这里用到了普通字符串的替换

现在可以再测试下了! 

<input type="text" autocomplete="off" id="price" autofocus="autofocus" onkeyup="value=value.replace(/[^\d^\.]+/g,'').replace('.','$#$').replace(/\./g,'').replace('$#$','.')">

 

补充: 只能输入数字和一个小数点的正则表达式

var reg = /^\d+$|^\d*\.\d+$/g;
reg.test(val) 用于判断

 

 

 

  

posted @ 2017-06-05 18:03  front-gl  阅读(54752)  评论(5)    收藏  举报