我对编码很陌生。我正在创建一个时事通讯表格,我需要人们通过输入姓名(仅字母(和有效的电子邮件地址进行注册。我正在尝试创建一个javascript函数,但它不能正常工作。功能是:
function validaIscrizione(username,email) {
var nameRegex = /^[a-zA-Z-]+$/
var emailRegex = /^(([^<>()[]\.,;: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(
username==''|| username==undefined || nameRegex.test(username)||
email== '' || email == undefined || emailRegex.test(email)
)
{return false;}
else{return true;}
}
var button = document.getElementById('btn_1');
button.onclick=function(){
var login=document.getElementById('username').value;
var password=document.getElementById('email').value;
var result = document.getElementById('result');
if(validaIscrizione(username,email)){
result.innerHTML = "Grazie per aver effettuato la registrazione";
}else{
result.innerHTML = "Dati non validi";
}
}
">
我是不是错过了什么?提前感谢
我修改了一点验证函数,并添加了注释和解释:
function validaIscrizione(username, email) {
const nameRegex = /^[a-zA-Z-]+$/;
const emailRegex = /^(([^<>()[]\.,;: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,}))$/;
// here you use short circuit for the falsy values like "" or undefined and validate the regex
const isUsernameValid = username && nameRegex.test(username);
const isEmailValid = email && emailRegex.test(email);
// here you return that is valid only if the two inputs pass your tests
return isUsernameValid && isEmailValid;
}