我想验证 <input>
用于检查用户名或电子邮件的表单元素。应该对同一个文本框进行验证
<input id="text1" type="text" placeholder="Enter username or email">
如果在输入标签本身中使用 pattern 属性会更容易。因为我想使用 jscript 编写验证消息。
最佳答案
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";
}
}
}
关于html - 在同一文本字段中验证用户名或电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37506319/