如何验证电子邮件、名字和姓氏



我尝试验证用户的名字、姓氏和电子邮件,如果有效则返回true,如果无效则返回false,然后要求用户在无效的情况下再次输入。通过用Javascript编写函数。对于只有字符串、连字符和空格的名称,以及只有字符串、htphen、下划线、@和句点的电子邮件,都是有效的。

1-我怎样才能摆脱"可接受";并将其设为返回真/假?2-我如何修改代码以验证电子邮件和first,lastname因为当我用firstname写@时,它会接受。

function validateText(text, validChares = "abcdefghijklmnopqrstuvwxyz -") {
let acceptable;
for (let t of text) {
acceptable = false;
for (let vc of validChares) {
if (t === vc) {
acceptable = true;
break;
}
}
if (!acceptable)
return false;
}
return true;
}
let validChars = "";
for (let i = 65; i <= 90; i++)
validChars += String.fromCharCode(i);
for (let i = 97; i <= 122; i++)
validChars += String.fromCharCode(i);
validChars += " @_-.";
//return validChars += " -";
let firstName = prompt("Enter your firstname");
if (validateText(firstName, validChars))
alert(`${firstName} is acceptable`);
else
alert(`${firstName} is not acceptable`);
while (!validateText(firstName)) {
firstName = prompt("Enter valid First Name:");
}
/**/
let lastName = prompt("Enter your lastname");
if (validateText(lastName, validChars))
alert(`${lastName} is acceptable`);
else
alert(`${lastName} is not acceptable`);
while (!validateText(lastName)) {
lastName = prompt("Enter valid Last Name:");
}
/**/
let email = prompt("Enter your email");
if (validateText(email, validChars))
alert(`${email} is acceptable`);
else
alert(`${email} is not acceptable`);
while (!validateText(email)) {
email = prompt("Enter valid Email:");
}
alert(`Registration data:nName: ${firstName}nSurname: ${lastName}nEmail: ${email}`)

您可以使用regex来测试您的姓名和电子邮件

对于名称,

const onValidName = (val) => {
// name can contain 
// CAPITAL ALPHABETS
// small alphabets
// whitespace
// hyphen
const nameRegex = /^[a-zA-Z- ]*$/
return nameRegex.test(val)
}
//it will log true if name is valid
console.log(onValidName(somename)  

对于电子邮件验证,您可以使用

const onValidEmail = (val) => {
// cheks for email is valid or not
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,}))$/
return emailRegex.test(val)
}
//return true if email is valid
console.log(onValidEmail(some email))

您可以通过这种方式不断向用户询问有效的姓名/电子邮件

let lastName = prompt("Enter your lastname");
if (onValidName(lastName))
alert(`${lastName} is acceptable`); //update UI or write in DB or do whatever you want
else{
alert(`${lastName} is not acceptable`); //or you can show error in UI
prompt("Enter your lastname"); //again ask for a valid name
}

剩下的所有[姓名、电子邮件等]的验证都可以用相同的方式进行

相关内容

  • 没有找到相关文章