-1

iam trying to verify multiple email addresses from txt file and then save valid emails to another txt file using nodejs. but it didn't work. the file has been read and it gives invalid to all emails even some of them are valid emails. here is my code

const fs = require("fs");

function validateEmail(email) {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
}

const inputData = fs.readFileSync("./input.txt", "utf8");

const emailAddresses = inputData.split("/n");

const validEmails = [];

for (const email of emailAddresses) {
  const isValid = validateEmail(email);
  if (isValid) {
    validEmails.push(email);
  }
  console.log(`${email}: ${isValid ? "valid" : "invalid"}`);
}

fs.writeFileSync("valid-emails.txt", validEmails.join("\n"), "utf8");

console.log(`Valid email addresses saved to "valid-emails.txt".`);

i tried to verify emails from txt file using regular expression. but it gives all of them invalid

  • This is a good opportunity for you to start familiarizing yourself with [using a debugger](https://stackoverflow.com/q/25385173/328193). When you step through the code in a debugger, which operation first produces an unexpected result? What were the values used in that operation? What was the result? What result was expected? Why? To learn more about this community and how we can help you, please start with the [tour] and read [ask] and its linked resources. – David Mar 29 '23 at 12:09
  • can you provide some of the emails you're testing, valid and not (what does input.txt look like) – depperm Mar 29 '23 at 12:09
  • sure, in my input.txt file mhassan7664@gmail.com hassan123@gmail.com muhammadhassan@7664@gmail.com – Muhammad Hassan Mar 29 '23 at 12:14
  • my console PS C:\Users\Hassan\Desktop\valadation> node app.js mhassan7664@gmail.com hassan123@gmail.com muhammadhassan@7664@gmail.com : invalid Valid email addresses saved to "valid-emails.txt". the new txt file is empty – Muhammad Hassan Mar 29 '23 at 12:22
  • 1
    A newline character is `\n` not `/n` – Lawrence Cherone Mar 29 '23 at 12:45

2 Answers2

0

Is the problem that you're splitting on /n instead of \n on line 8 and that because of this, your array contains only one item and it's the entire content of your input file?

Add a console.log(emailAddresses) and that should confirm it for you.

  • after \n the console looks like this: : invalid64@gmail.com : invalid@gmail.com : invalidassan@7664@gmail.com : invalid Valid email addresses saved to "valid-emails.txt". – Muhammad Hassan Mar 29 '23 at 12:26
0

try this way

const fs = require("fs");

const inputData = fs.readFileSync("./input.txt", "utf8");

const validEmails = inputData.split("\n").filter(email => {
    const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (re.test(email)) {
        return email;
    }
});

fs.writeFileSync("valid-emails.txt", validEmails.join("\n"), "utf8");
Bharath
  • 390
  • 1
  • 6