使用if语句检查用户名中字母和数字的组合
Using if statements to check for combination of letters and numbers in username
昨天声明的Javascript。我正在使用JavaScript编写客户端表单验证,并在代码中使用了一堆if语句。
就是这样。:
function validateloginform() { //login page validation test //
var username = document.forms["form"]["username"].value;
var password = document.forms["form"]["password"].value;
var verifypassword = document.forms["form"]["verifypassword"].value;
if (document.form.username.value == null || document.form.username.value == "") {
alert("Username is blank...it must be entered");
document.form.username.focus();
return false;
}
if (document.form.username.value.length != 8) {
alert("Username must be 8 characters long");
document.form.username.focus();
return false;
} else {
alert("Correct");
return true;
}
}
我如何才能更具体地使用我的语句来包括数字和字母([a-z]或[0-9])字符的组合。
如果用户名或密码不包含字母和数字的组合,则返回false。还有,有没有办法包括特殊字符?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
查看该链接,了解Javascript的正则表达式教程。如果你想切入正题,这里有一个例子(来自教程,但我添加了一些解释)。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/javascript">
// Create a regular expression
// This regular expression is used to check the user's input phone number is in
// a common phone number format.
var re = /(?:'d{3}|'('d{3}'))([-'/'.])'d{3}'1'd{4}/;
function testInfo(phoneInput){
// The exec() call below checks if the phoneInput.value matches the regex re
// which was defined above.
var OK = re.exec(phoneInput.value);
// OK will be true or false depending on if phoneInput.value matched the regex.
if (!OK)
window.alert(RegExp.input + " isn't a phone number with area code!");
else
window.alert("Thanks, your phone number is " + OK[0]);
}
</script>
</head>
<body>
<p>Enter your phone number (with area code) and then click "Check".
<br>The expected format is like ###-###-####.</p>
<form action="#">
<input id="phone"><button onclick="testInfo(document.getElementById('phone'));">Check</button>
</form>
</body>
相关文章:
- 如何在谷歌可视化中组合数字和模式格式化程序
- 将数组中的所有数字组合相加
- 获取对象的所有可能组合,其中值的总和与数字匹配
- 给定一个4位锁,其中每个数字可以是0、1、2、3或4,我如何计算所有加起来为4的组合
- Javascript给定了一个数字,我想要所有可能的组合和元素数组
- 显示给定输入数字的数据集中字母表的所有可能组合
- 当前面的数字或前面字符的组合未知时提取字符串
- 与数字组合的唯一性,与顺序无关
- 从组合框中获取值并向其添加一个数字
- 将 2 个数字组合起来用作对象键的有效方法是什么
- Captcha IMG/数字组合
- 对具有字母和数字组合的数据进行排序,该数据在javascript中的json数组中具有值
- 具有唯一结果的两个数字组合的精简算法
- 用于字母/数字组合的正则表达式
- Knockout:为数字组合2个自定义绑定-金融数据
- JavaScript Tic Tac Toe -查找数组中所有可能的数字组合
- 试图将随机化的数字组合起来
- 将n个数字组合成两个唯一的组
- Javascript - 排序字母数字组合
- 字母和数字组合与正则表达式匹配