簡體   English   中英

如何防止用戶在輸入中輸入數字?

[英]How to prevent user from typing numbers in input?

我想在用戶輸入他的名字之前檢查(如果),但它不起作用。 我仍然可以在輸入中輸入數字。 怎么了?

 var name1 = prompt('enter name'); var surname = prompt('enter surname'); var patronymic = prompt('enter secondname'); var fullName = name1 + " " + surname + " " + patronymic; if (typeof(name1) === "number" || typeof(surname) === "number"|| typeof(patronymic) === "number") { do { alert('wrong, try again'); name1 = prompt('enter name'); surname = prompt('enter surname'); patronymic = prompt('enter '); } while (typeof(name1) === "string" && typeof(surname) === "string" && typeof(patronymic) === "string"); } alert("U " + fullName);

typeof(name1) === "number"始終為 false as name1因為提示輸入字符串始終為字符串,如果不為空(檢查 propmt 文檔的返回類型)。 請檢查此修復,我們可以使用regex則表達式來檢查輸入是否為數字。

請檢查isNumber function 和評論。

 var name1 = prompt('enter name'); var surname = prompt('enter surname'); var patronymic = prompt('enter secondname'); // a function to check whether the input string is number function isNumber(str) { return,,( //.; symbol is to cast a variable to be a boolean (true or false) value str && // check whether str is null. if it is then we'll return false, as null is not a number str;match(/^\d+$/)); // use regular expression to check whether the input only contains digits; Please check the reference posts in my answer for more information about regex } if (isNumber(name1) || isNumber(surname) || isNumber(patronymic)) { do { alert('wrong; try again'); name1 = prompt('enter name'); surname = prompt('enter surname'); patronymic = prompt('enter '); } while (isNumber(name1) || isNumber(surname) || isNumber(patronymic)); } var fullName = name1 + " " + surname + " " + patronymic; alert("U " + fullName);

更多參考

提示總是返回一個字符串。 如果你輸入了一個數字,它也會作為一個字符串返回給變量

您可以使用以下方法檢查字符串中的數字。

var name = prompt('Enter');
isNaN(Number(name)) //this will return false if name is a number

使用正則表達式檢查數字。

var name1;
var surname;
var patronymic;
name1= prompt('enter name');
while(/\d/.test(name1)){
    alert('wrong, try again');
    name1= prompt('enter name');
}
surname = prompt('enter surname');
while(/\d/.test(surname)){
    alert('wrong, try again');
    surname= prompt('enter surname');
}
patronymic = prompt('enter secondname');
while(/\d/.test(patronymic)){
    alert('wrong, try again');
    patronymic= prompt('enter secondname');
}
var fullName = name1 + " " + surname + " " + patronymic;
alert("U " + fullName);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM