-1

如何使用正则表达式验证名称部分中的表单 /^[a-zA-Z]{2,20}$/

我希望用户在 az 或 AZ 中输入他们的姓名,其中不少于 2 个字符且不超过 20 个字符。

有人可以帮忙吗?

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Can Validate Input</h2>

<p>Please input a number between 1 and 10: <input id="numb"> <span id="demo"></span> </p>
<p>Please input your name <input id="name"> <span id="demo2"></span></p> 

<button type="button" onclick="myFunction()">Submit</button>

<script>
    function myFunction() {
    var x, text;
    var y, text2;

        // Get the value of the input field with id="numb"
    x = document.getElementById("numb").value;
    y = document.getElementById("name").value;

// If x is Not a Number or less than one or greater than 10
if (x == ""){
    text = "Age must be filled out.";
}
else if (isNaN(x) || x < 1 || x > 10) {
    text = "Digits only or enter age between 10 and 120.";}
else {
    text = "Age Input OK";
}
document.getElementById("demo").innerHTML = text;

if ( y == ""){
text2 = "Name must be filled out.";
}

** 下面这行是我需要帮助的地方:**

else if (y != /^[a-zA-Z]{2,20}$/){
text2= "Enter letters 2 to 20 only";
}

///
else {
text2 = "name is ok";
}
document.getElementById("demo2").innerHTML = text2;
}
4

2 回答 2

0

使用变量并将正则表达式模式分配给变量。然后使用 search() 函数来评估输入。

// variable = pattern expression:
 
reg = /^[a-zA-Z]{2,20}$/;

// change else if statement to:

else if (y.search(reg)){ 
    text2= "Enter letters 2 to 20 only";
}
于 2020-11-19T23:17:25.217 回答
0

使用适用于正则表达式的 javascripttest方法

else if (/^[a-zA-Z]{2,20}$/.test(y){
text2= "Enter letters 2 to 20 only";
}

或者为了更好的代码可读性使用这个

const testRegex = /^[a-zA-Z]{2,20}$/
else if (testRegex.test(y){
text2= "Enter letters 2 to 20 only";
}

更新:不支持号码

如果你不想要一个数字,你可以使用下面的正则表达式

const with_no_numbers = /^[a-zA-Z\D]{2,20}$/
于 2020-11-19T18:58:26.647 回答