javascript 仅限字母
javascript Letters only
我在 javascript 上创建了一个测验,一旦用户回答正确 4/6 或更多,他们将被要求输入名字、姓氏,然后得到一个随机的 4 位数代码。我遇到问题的部分是只制作 FirstName 和 LastName 字母,也不允许和空提示。
有人知道我如何在其中实施正则表达式吗?
有人能帮忙吗?
function getAnswers(){
var amountCorrect = 0;
for(var i = 1; i <= 10; i++) {
var radios = document.getElementsByName('q'+i);
for(var j = 0; j < radios.length; j++){
var radio = radios[j];
if(radio.value == "1" && radio.checked) {
amountCorrect++;
}
}
}
alert("Correct number of answers: " + amountCorrect + " / 6");
if (amountCorrect <= 3){
alert("You have not passed on this occasion. You will now be taken back to the homepage.");
window.history.go(-1); // Go back a step
}
else{
var firstname = prompt("Please enter your first name.");
var lastname = prompt("Please enter your last name.");
alert("Your login Code for the store is: " + firstname.substring(1, 0) + lastname.substring(1, 0) + (generateCode())); // Do the generateCode function
close();
}
}
试试这个..
var alphaExp = /^[a-zA-Z]+ [a-zA-Z]+$/;
var firstname =prompt("Please enter your first name And Last Name","");
if (firstname ==null || firstname =="")
{
alert("First and last name must be filled out!");
location.reload(true);
}
else if (!firstname.matches(alphaExp))
{
alert("Name must contain letters only!")
location.reload(true);
}
else{ // your code here.
}
/^[a-zA-Z]+$/
这对你有用。
试试这个正则表达式:
^[A-Z][a-zA-Z]*$
这个正则表达式匹配一串字母:
- 以字母 A-Z 开头
- 只允许 a-z 和 A-Z 中的字母
- 它不会匹配空行或任何其他字符。
我在 javascript 上创建了一个测验,一旦用户回答正确 4/6 或更多,他们将被要求输入名字、姓氏,然后得到一个随机的 4 位数代码。我遇到问题的部分是只制作 FirstName 和 LastName 字母,也不允许和空提示。
有人知道我如何在其中实施正则表达式吗?
有人能帮忙吗?
function getAnswers(){
var amountCorrect = 0;
for(var i = 1; i <= 10; i++) {
var radios = document.getElementsByName('q'+i);
for(var j = 0; j < radios.length; j++){
var radio = radios[j];
if(radio.value == "1" && radio.checked) {
amountCorrect++;
}
}
}
alert("Correct number of answers: " + amountCorrect + " / 6");
if (amountCorrect <= 3){
alert("You have not passed on this occasion. You will now be taken back to the homepage.");
window.history.go(-1); // Go back a step
}
else{
var firstname = prompt("Please enter your first name.");
var lastname = prompt("Please enter your last name.");
alert("Your login Code for the store is: " + firstname.substring(1, 0) + lastname.substring(1, 0) + (generateCode())); // Do the generateCode function
close();
}
}
试试这个..
var alphaExp = /^[a-zA-Z]+ [a-zA-Z]+$/;
var firstname =prompt("Please enter your first name And Last Name","");
if (firstname ==null || firstname =="")
{
alert("First and last name must be filled out!");
location.reload(true);
}
else if (!firstname.matches(alphaExp))
{
alert("Name must contain letters only!")
location.reload(true);
}
else{ // your code here.
}
/^[a-zA-Z]+$/
这对你有用。
试试这个正则表达式:
^[A-Z][a-zA-Z]*$
这个正则表达式匹配一串字母:
- 以字母 A-Z 开头
- 只允许 a-z 和 A-Z 中的字母
- 它不会匹配空行或任何其他字符。