所以我在这里被卡住了。我想要用户名的约束,它不应该以任何特殊字符开头。我认为正则表达式不起作用。任何人都可以帮助它的工作吗?
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>username test</title>
</head>
<body>
<form id="form1" onsubmit="user()" name="form1" method="post" action="">
<p align="center"> <img src="gecp.png" width="144" height="144" alt="gecp" /></p>
<p align="center">
<label for="username">Username</label>
<input type="text" name="username" id="user" required/>
</p><p id="p1"> </p>
<p align="center">
<label for="pass">Password</label>
<input type="password" name="pass" id="pass" required/>
</p><p id="p2"> </p>
<p align="center">
<input name="sub" type="submit" id="sub" value="Submit" />
</p>
</form>
<div align="center"></div>
<script type="text/javascript">
function user(){
var name1=document.getElementById("user").value;
var u1=/^[a-zA-Z]$/;
if(name1.value.match(u1)){
return true;
}
else {
document.getElementById("p1").innerHTML= "Invalid Input";
name1.focus();
return false;}
}
</script>
</body>
</html>
答案 0 :(得分:0)
match
函数将返回一个包含字符串匹配组的数组。您需要的是test
功能。
function user(){
var name1=document.getElementById("user").value;
var u1=/ˆ(\w+)(.+)$/;
if(u1.test(name1)){
return true;
} else {
document.getElementById("p1").innerHTML= "Invalid Input";
name1.focus();
return false;
}
}
您不需要在value
上调用name1
属性,因为您在检索到值时已经调用了该属性。
我还提供了一个优化的代码:
function user(){
var name1=document.getElementById("user").value;
if(!/ˆ(\w+)(.+)$/.test(name1)) {
document.getElementById("p1").innerHTML= "Invalid Input";
name1.focus();
return false;
}
return true;
}
关于你的正则表达式,根据我的理解,你不需要在名称的开头有任何特殊字符。因此,我使用\w
仅匹配单词([a-Z]
)。如果你也可以使用负向前瞻来确保你的字符串不以任何特殊字符开头。 Here是一个regex101来测试你的案例。
否定前瞻看起来像(?![$%?&*])(.+)$
Here是一个带有否定前瞻的例子