如何使用正则表达式验证名称部分中的表单 /^[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;
}