如何将 html 输入设置为仅接受数字和电子邮件 ID?
<input id="input" type="text" />
最佳答案
正如上面评论中提到的,如果您想同时接受 8 位电话号码和电子邮件地址,这应该可行:
HTML 表单代码:
<form onsubmit="return validateInput()">
<input type="text" name"mail_or_phone"/>
</form>
JS 验证:
function validateInput()
{
var fieldValue= document.getElementById("mail_or_phone").value;
// taken from this SO post: http://stackoverflow.com/questions/7126345/regular-expression-to-require-10-digits-without-considering-spaces
var phoneValidation= /^([\s\(\)\-]*\d[\s\(\)\-]*){8}$/;
var mailValidation= /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (fieldValue.match(phoneValidation)) {
// correct phone structure
return true;
} else if (fieldValue.match(mailValidation)) {
// correct mail format
return true;
} else {
// incorrect structure
return false;
}
}
这是一个fiddle显示上述代码的示例。如果答案不正确,您应该显示某种警告(未包含在代码中)。
关于javascript - HTML 输入仅接受数字和电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41666034/