我想验证表单的<input>
元素以检查用户名或电子邮件。应该对同一个文本框进行验证
<input id="text1" type="text" placeholder="Enter username or email">
如果在输入标记本身中使用pattern属性会更容易。因为我想使用jscript编写验证消息。
答案 0 :(得分:1)
或者你想要这样的东西
<input id="text1" type="text" placeholder="Enter username or email">
<input type="button" id="submit" value="Submit" onclick="validate()" />
<script>
function validate() {
var field = document.getElementById('text1').value;
// CHeck if email
if (/\@/.test(field)) {
// Validate email address
}
else {
// Validate username
}
}
</script>
答案 1 :(得分:1)
function validate(field) {
// var field = document.getElementById('text1').value;
// CHeck if email
if (/\@/.test(field)) {
// Validate email address
if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(field)) {
return (true)
}
console.log("You have entered an invalid email address!");
return (false)
} else {
// Validate username
var error = "";
var stripped = field.replace(/[\(\)\.\-\ ]/g, '');
if (stripped == "") {
alert("You didn't enter a phone number.");
error = "You didn't enter a phone number.";
} else if (isNaN(parseInt(stripped))) {
phone = "";
error = "The phone number contains illegal characters.";
alert("illegal characters.");
} else if (!(stripped.length == 10)) {
alert("wrong length");
phone = "";
error = "The phone number is the wrong length. Make sure you included an area code.\n";
}
}
}