Window.prompt仅接受数值

时间:2018-09-28 10:20:05

标签: javascript regex

我正在尝试(尽管没有成功)创建一个window.prompt,它将仅接受 数值(0、1、2、3,...),但是我认为我做错了什么。看我的功能。我有误会吗?我如何在代码中使用此正则表达式/^[0-9.,]+$/

<script>
    function save3() {
      var pn = 4; 
      do{
        var selection = parseInt(window.prompt("Give the User Id:", "Type a number!"), 10);
if (selection != (/^[0-9.,]+$/)){
    window.alert("xana");       
    }
        }while(isNaN(selection));
    $("#user_id").val(selection)
      //$("#user_id").val(prompt("Give the User Id:"))
      do{
        var selection2 = parseInt(window.prompt("Give the Book Id:", "Type a number!"), 10);
        }while(isNaN(selection2));
    $("#book_id").val(selection2)
      //$("#book_id").val(prompt("Give the Book Id:"))
      do{
        var selection3 = parseInt(window.prompt("Give the Game Id:", "Type a number!"), 10);
        }while(isNaN(selection3));
    $("#game_id").val(selection3)
      //$("#game_id").val(prompt("Give the Game Id:"))
      $("#site_id").val(pn)
    }
  </script>

2 个答案:

答案 0 :(得分:0)

您可以使用RegExp.test()来检查输入内容,例如:

const isInteger = /^(\d)+$/g;
if(isInteger.test(selection)) {
  console.log('Correct input!');
  // ... code
}

答案 1 :(得分:0)

您应将代码减少到再现该问题所需的最低限度,例如:

 var selection = parseInt(window.prompt("Give the User Id:", "Type a number!"), 10);

if (selection != (/^[0-9.,]+$/)){
  console.log('fail');
} else {
  console.log('pass');
}

这将为任何值返回“失败”,因为您正在针对一个永远不能相等的正则表达式对象测试数字。

如果只希望用户输入数字,句点(。)和逗号(,),则将输入的文本保留为字符串,并使用 test 方法对其进行测试。我也颠倒了测试,因此更有意义:

var selection = parseInt(window.prompt("Give the User Id:", "Type a number!"), 10);

if ( /^[0-9.,]+$/.test(selection)) {
  console.log('pass');

} else {
  console.log('fail');
}

相关问题