当输入类型=“数字"时,正则表达式验证是否有效? [英] Does regex validation work when input type="number"?

查看:31
本文介绍了当输入类型=“数字"时,正则表达式验证是否有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在输入字段上使用 type="number" 时,regex 验证似乎不起作用.

When using type="number" on an input field, regex validation does not appear to work.

<input type="number" step="any" min="0" max="24" value="0">

使用 step, min, max 的新的基于浏览器的验证按预期工作.但是这在浏览器中不一致?

The new broswer based validation using step, min, max works as expected. However this is not consistent accross browsers?

http://jsfiddle.net/EkL3k/1/

问题

如何使用正则表达式验证数字字段?

How to make a number field validate using regular expression?

如果有人有信息,我也对区分数字和文本字段的其他因素感兴趣.

注意事项

我发现检查空字符串会导致验证触发如果不满足数字字段的条件.

I have discovered that checking for an empty string causes validation to fire IF the conditions on the number field are not met.

推荐答案

数字字段执行自己的验证,如果它包含非数字字符,该值将自动删除,直到给出正确的值.您可以通过 console.log(value) 看到这一点.

A number field performs its own validation, if it contains a non-numerical character, the value will automatically be removed until a correct value is given. You can see this with a console.log(value).

所以你也可以检查一个空字符串

So you could also check for an empty string

function check(value, msg) {
  var valid = ((value != '') && /^\d*\.?\d*$/.test(value));    
  if (valid) {
      document.getElementById(msg).style.display = "none";
  } else {
      document.getElementById(msg).style.display= "inline";
  }
  return valid;
}

http://jsfiddle.net/EkL3k/6/

这篇关于当输入类型=“数字"时,正则表达式验证是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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