How can I validate email,firstname and lastname? - javascript

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}`)

You can instead use regex to test your name and email
for name,
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)
for email validation, you can use
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))
you can keep asking user for a valid name/email by this way
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
}
rest all validations for [name, email, etc] can be done in the same way

Related

Javascript call back function not working as expected. Trying to make sure all code is complete before the finalization logic is executed

I am trying to have a summary section in my website that will take all the results from other functions and display the information. I created the following functions and call path to try and get this but it appears that the callback is still being called before the largest function finishes.
Office.onReady(info => {
if (info.host === Office.HostType.Outlook) {
document.getElementById("app-body").style.display = "flex";
mainprocessing(finalization);
}
});
function mainprocessing(callback){
console.log("main processing")
reviewEmailInfo();
attachmentCheck();
checkBodyforLinks();
checkmsgforriskywords();
callback();
}
function finalization(){
console.log("entering finalization");
document.getElementById("riskscore").innerHTML = "This email has a riskscore of " + riskScore;
}
I put console.logs into each function at the beginning and end and this is what is in the logs
main processing taskpane.js:43
entering review email taskpane.js:122
entering attachment check taskpane.js:137
leaving attachment check taskpane.js:174
entering check body taskpane.js:192
leaving check body taskpane.js:196
entering check risky words taskpane.js:210
entering leaving check risky taskpane.js:38
entering finalization VM72 taskpane.js:9931
leaving review email VM72 taskpane.js:9002
[WDS] Live Reloading enabled.client:52
[WDS] Live Reloading enabled.
leaving review email taskpane.js:106
function checkBodyforLinks(){
console.log("entering check body");
Office.context.mailbox.item.body.getAsync(
"html",
{ asyncContext: "This is passed to the callback" },
function callback(result) {
var parser = new DOMParser();
var bodyHtml = parser.parseFromString(result.value, "text/html");
//need to add check to ignore mailto: links
var linkDomains = [], links = bodyHtml.links;
document.getElementById("linkCheck").innerHTML = "No links found within email body";
for (var i = 0; i < links.length; i++){
linkDomains.push(links[i].href);
}
if (linkDomains.length > 0){
document.getElementById("linkCheck").innerHTML = "There are " + links.length+1 +"links in the email body";
}
}
);
console.log("leaving check body");
}
console.log("entering review email");
Office.context.mailbox.item.getAllInternetHeadersAsync(
function(asyncResult) {
if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
var headers = asyncResult.value;
var ReplyTo = headers.replace(" ","").match(/Return-Path:(.*)/);
if (ReplyTo.length != null){
var cleanEmail = ReplyTo[1].substring(1,ReplyTo[1].length);
if(cleanEmail == Office.context.mailbox.item.sender.emailAddress){
document.getElementById("reply-match").innerHTML= "The from and reply email address match";
}else{
riskScore += 5;
document.getElementById("reply-match").innerHTML= "The from and reply email address DO NOT MATCH. The sender is:" + Office.context.mailbox.item.sender.emailAddress + " and the reply addres is: " + cleanEmail;
}
}
var ARCAuthResult = headers.replace(" ","").match(/ARC-Authentication-Results:(.*)/);
var dkimChk = false;
var spfChk = false;
if(ARCAuthResult != null){
if(ARCAuthResult[1].search("spf=pass")){
spfChk = true;
}
if(ARCAuthResult[1].search("dkim=pass")){
dkimChk = true;
}
}else{
var AuthResult = headers.replace(" ","").match(/Authentication-Results:(.*)/);
if(AuthResult.length != null){
if(AuthResult[1].search("spf=pass")){
spfChk = true;
}
if(AuthResult[1].search("dkim=pass")){
dkimChk = true;
}}}
if(spfChk == true & dkimChk==true){
document.getElementById("dkimspfchk").innerHTML = "Both DKIM and SPF are safe";
}else if(spfChk == true){
riskScore += 5;
document.getElementById("dkimspfchk").innerHTML = "DKIM check failed";
}else if(dkimChk == true){
riskScore += 5;
document.getElementById("dkimspfchk").innerHTML = "SPF check failed";
}else{
riskScore += 10;
document.getElementById("dkimspfchk").innerHTML = "SPF amd DKIM check failed";
}
//Check for domain match between sender and reciever
var domainIndex = Office.context.mailbox.item.sender.emailAddress.indexOf("#");
var senderDomain = Office.context.mailbox.item.sender.emailAddress.slice((domainIndex+1), Office.context.mailbox.item.sender.emailAddress.length);
var receiverAddress = headers.replace(" ","").match(/To:(.*)/);
if (receiverAddress.length != null){
domainIndex = receiverAddress[1].indexOf("#");
var recieverDomain = receiverAddress.slice((domainIndex+1),receiverAddress.length-1);
if(senderDomain == recieverDomain){
document.getElementById("domainMatch").innerHTML = "This email comes from with your domain";
}else {
riskScore += 1;
document.getElementById("domainMatch").innerHTML = "This message comes from an external email address";
console.log("risk score after domain " + riskScore);
}
}
//var domainAge = domainWhois(senderDomain);
console.log("leaving review email");
return;
} else {
if (asyncResult.error.code == 9020) {
// GenericResponseError returned when there is no context.
// Treat as no context.
} else {
console.log("error");
}
}
}
);
return;
}

Pull number value from string

So I need to pull a number value from a string. I currently have a working solution but I feel that maybe I can improve this using a regular expression or something.
Here is my working solution
var subject = "This is a test message [REF: 2323232]";
if(subject.indexOf("[REF: ") > -1){
var startIndex = subject.indexOf("[REF: ");
var result = subject.substring(startIndex);
var indexOfLastBrace = result.indexOf("]");
var IndexOfRef = result.indexOf("[REF: ");
var ticketNumber = result.substring(IndexOfRef + 6, indexOfLastBrace);
if(!isNaN(ticketNumber)){
console.log("The ticket number is " + ticketNumber)
console.log("Valid ticket number");
}
else{
console.log("Invalid ticket number");
}
}
As you can see I'm trying to pull the number value from after the "[REF: " string.
// Change of the text for better test results
var subject = "hjavsdghvwh jgya 16162vjgahg451514vjgejd5555v fhgv f 262641hvgf 665115bs cj15551whfhwj511";
var regex = /\d+/g;
let number = subject.match( regex )
console.log(number)
It Will return array for now, and if no match found, it will return null.
For most of the time, when i used this regex i get perfect result unless if string contains decimal values.
var str = 'This is a test message [REF: 2323232]'
var res = str.match(/\[REF:\s?(\d+)\]/, str)
console.log(res[1])
If you don't want to use a regular expression (I tend to stay away from them, even though I know they are powerful), here is another way to do it:
// Your code:
/*var subject = "This is a test message [REF: 2323232]";
if(subject.indexOf("[REF: ") > -1){
var startIndex = subject.indexOf("[REF: ");
var result = subject.substring(startIndex);
var indexOfLastBrace = result.indexOf("]");
var IndexOfRef = result.indexOf("[REF: ");
var ticketNumber = result.substring(IndexOfRef + 6, indexOfLastBrace);
if(!isNaN(ticketNumber)){
console.log("The ticket number is " + ticketNumber)
console.log("Valid ticket number");
}
else{
console.log("Invalid ticket number");
}
}*/
// New code:
const subject = "This is a test message [REF: 2323232]";
const codeAsString = subject.split('[REF: ')[1]
.split(']')
.join('');
if (!isNaN(parseInt(codeAsString))) {
console.log('Valid ticket number: ', parseInt(codeAsString));
}
else {
console.log('Invalid ticket number: ', codeAsString);
}
This will extract number
var subject = "This is a test message [REF: 2323232]";
var onlyNum = subject.replace(/.*(:\s)(\d*)\]$/,'$2');
console.log(onlyNum)
Here, same but the number is now a real int
var subject = "This is a test message [REF: 2323232]";
var onlyNum = parseInt(subject.replace(/.*(:\s)(\d*)\]$/,'$2'));
console.log(onlyNum)

How to find a word in a string?

The challenge is to "find Waldo." I'm trying to figure out how to find a word in a function/string." Return the index of where in the string 'Waldo' starts."
function findWaldo(str) {
var waldoPosition;
return waldoPosition
}
Simple task to do:
function findWaldo(str) {
return str.indexOf("waldo"); //the string you are looking for
}
It is explained quite well here.
There should be a library that does it easily, like string.indexOf, but you can do it manually with this algorithm:
int count = 0;
string yourText = "This is waldo?";
string toSearch = "waldo";
for (int x = 0; x < yourText.Lenght; x++)
{
if(yourText[x] == toSearch[0])
if((count + 1) == toSearch.Lenght)
return x;
else
count = 0;
//here we'd say ehh there's not Waldo on the string
}
To find a word or letter you can use x.indexOf method, hope to below code helps.
// Question
const findWord = (str, findWord) =>{
let total = ""
let error = false
let errorMessage = "";
if(str != null && str != ""){
error = false
if(!str.indexOf(findWord)){
total = `there is no ${findWord} in str peremeter.
`
}else{
total = `the position of ${findWord} is ${str.indexOf(findWord)}`
}
}else{
error = true;
errorMessage = "Please fill the str perimeter."
return errorMessage
}
return total
}
// Calling Function
console.log(findWord("Hello World", "World"))

Limiting length of each word in a string

Is there a way to limit the length of each word in a string?
For example:
Loop through each word in a string
If a word is longer than X amount of characters, display a pop up message and do not submit the form.
Edit: My final code:
$("#comment-form").submit(function(event) {
var str = $("#comment-box").val(), limit = 135;
var wordList = str.split(' ');
$(wordList).each(function(i, word) {
if(word.length > limit) {
alert("Your comment has a string with more than " + limit + " characters. Please shorten it.");
event.preventDefault();
}
});
});
Try this:
var str = "This is the test string that contains some long words";
var wordList = str.split(' ');
var limit = 4;
$(wordList).each(function(i, word){
if(word.length >= limit){
alert(word);
}
});
You can use the following function
<script>
var string = "Please be sure question to answer the question";
function checkWordLength(string)
{
var string_array = string.split(" ");
for(var i=0; i<string_array.length; i++)
{
var word = string_array[i];
var word_length = word.length;
if(word_length>6) return false;
}
}
checkWordLength(string);
</script>
jsFiddle
function CheckString(string, character_limit)
{
var word = /\w+/igm;
var match;
while((match = word.exec(string)) !== null) {
if(match[0].length > character_limit)
{
alert(match[0]);
return false;
}
}
return true;
}
var character_limit = 5;
var string = 'this is a string of words and stuff even';
CheckString(string, character_limit);
This example uses regular expressions when it returns false make sure to either return false from the onSubmit method of your form.

validate a user registration form

I have a user registration form. I already use validation to check if all fields are filled. I need to validate email and mobile number using javascript and alert using an alertbox if its not valid. Please help
the code is
var name = $("#name").val();
var inst = $("#inst").val();
var email = $("#email").val();
var mobile = $("#mobile").val();
var dataString = 'name='+ name + '&inst='+ inst + '&email='+ email +'&mobile='+ mobile;
if(name==''|| inst=='' || email=='' || mobile=='')
{
alert("Please Enter all the Fields");
}
else
{ //rest of code comes here
var emailRe = /^\w+([\.\-]?\w+)*#\w+([\.\-]?\w+)*\.(\w{2}|(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum))$/;
var phoneRe = /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/;
var email_address = $('#email').val();
var phone_number = $('#phone').val();
if(emailRe.test(email_address) === false){
alert(email_address + ' is invalid');
}
if(phoneRe.test(phone_number) === false){
alert(phone_number + ' is invalid');
}
Reference: Regular Expressions Field Validation

Categories