[英]Window.prompt accept only numeric values
I am trying (unsuccessfully although) to make a window.prompt which will accept only numeric values (0,1,2,3,...) but I believe that something I am doing wrong. 我正在尝试(虽然未成功)制作一个仅接受数值(0、1、2、3,...)的window.prompt,但我认为我做错了。 Look at my function. 看我的功能。 Am I missunderstanding something? 我有误会吗? how can i use this regex /^[0-9.,]+$/
in my code? 我如何在我的代码中使用此正则表达式/^[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>
You can use RegExp.test()
to check your input like: 您可以使用RegExp.test()
来检查您的输入,例如:
const isInteger = /^(\d)+$/g;
if(isInteger.test(selection)) {
console.log('Correct input!');
// ... code
}
You should reduce your code to the minimum required to reproduce the issue, eg: 您应该将代码减少到再现该问题所需的最低限度,例如:
var selection = parseInt(window.prompt("Give the User Id:", "Type a number!"), 10); if (selection != (/^[0-9.,]+$/)){ console.log('fail'); } else { console.log('pass'); }
This returns "fail" for any value because you're testing a number against a regular expression object, which can never be equal. 这将为任何值返回“失败”,因为您正在针对一个永远不能相等的正则表达式对象测试一个数字。
If you want the user to only enter digits, period (.) and comma (,), then leave the entered text as a string and test it using the test method. 如果只希望用户输入数字,句点(。)和逗号(,),则将输入的文本保留为字符串,并使用测试方法对其进行测试 。 I've also inverted the test so it makes more sense: 我也颠倒了测试,因此更有意义:
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'); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.