[英]How can I use javascript to index input from a HTML form?
I have a form where you must enter a username, but the username cannot start or end with a period (.).我有一个表单,您必须在其中输入用户名,但用户名不能以句点 (.) 开头或结尾。 This is what I have so far, I feel like I'm close.
这是我到目前为止所拥有的,我觉得我很接近。 I think I am making an error in the.value[0] parts.
我想我在 .value[0] 部分出错了。
//Checking Username
if (document.getElementById("uName").value[0] == "." || document.getElementById("uName").value[-1]) {
document.getElementById("notification4").innterHTML ="Cannot have period at start or end.";
submitForm = false;
} else {
document.getElementById("notification4").innerHTML="";
}
My second question is how would I be able to stop the same character from repeating twice in a row?我的第二个问题是如何阻止同一个字符连续重复两次? For example you can't have (--), (//), (%%), (**) etc. I would prefer a similar method to use like above or with regex.
例如,您不能使用 (--)、(//)、(%%)、(**) 等。我希望使用类似的方法来使用上述方法或正则表达式。
This is the forms HTML:这是 forms HTML:
<label for="uName"> Username: </label><br>
<input type="text" id="uName" name="uName"> <br>
<div class= "error" id="notification4"></div><br>
You can use regular expression and the RegExp.prototype.test() function:您可以使用正则表达式和RegExp.prototype.test() function:
const regex = /^[.]|[.]$|[^a-zA-Z0-9]{2}/g;
if(regex.test(str)) {
//code when it matches
} else {
//code when it doesn't match
}
This checks if the first or last character is a dot (^[.]|[.]$) and if there is any character repeated twice that is not a letter or number ([^a-zA-Z0-9]{2}).这将检查第一个或最后一个字符是否为点 (^[.]|[.]$) 以及是否有任何重复两次的字符不是字母或数字 ([^a-zA-Z0-9]{2 })。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.