I try to validate firstname,lastname and email taken by user and return true if its valid or return false if it is not valid then ask the user to enter again as long as it is not valid.By writing a function in Javascript. For names just string,hyphen and whitespace and for email just string,htphen,underscore,@ and dot is valid.
1-How can i get rid of "acceptable" and just make it as return true/false? 2-How can I modify the code to validate both the email and first,lastname because when i write @ for example in firstname it accepts.
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}`)