我想插入一个可以接受html表单中的用户名和电子邮件地址的字段!
<label>Username or e-mail address: </label>
<input type="text">
此外,我认为有必要使用Javascript进行验证。
您可以通过id:获取元素
<input type="text" id="input" />
const regEx = new RegExp('^(([^<>()[]\.,;: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,}))$')
const inputElement = document.getElementById('input');
if(inputElement && inputElement.value){
if(inputElement.value.match(regEx)
console.log('Is Email')
else
console.log('Is Username')
}
Regex会检查输入的是电子邮件还是用户名。
给您的输入一个id:
<input type="text" id="inputID" />
您可以使用jQuery检查inputID是否为电子邮件:
var inputId = $('#inputID').val();
if (inputId.indexOf('@') > -1)
{
alert("this is an email");
} else {
alert("this is not an email");
}
如果您不喜欢jQuery,可以使用JavaScript设置变量。您只需要使用getelementbyId。