Check a CSV for CRM Import Rules in Google Sheets

By Andrew Apell, creator of Flookup Data Wrangler. Updated

About the Author

Andrew Apell is the creator of Flookup Data Wrangler and has built data cleaning tools for Google Sheets since 2018.
Every Flookup result described here can be checked in the documentation.
Read Our Story for the background or contact the team with any questions about this post, including corrections, unclear steps or use cases we have not covered yet.

Key Takeaways

  • A CRM import fails on formatting errors long before it reaches the interesting data decisions, which is why a pre-flight check in Google Sheets saves an afternoon of retries.
  • One Apps Script pass reports every bad row.
  • REGEXMATCH, LEN, COUNTIF and TEXTJOIN give a formula route for a one-off file, without adding helper columns to the working sheet.
  • The script checks file hygiene, not CRM picklists.

Introduction

A contact CSV reaches the CRM, the import stops and the error message names one row. You fix that row, upload again and the next row fails. A file with a few hundred contacts can take an afternoon to push through a process that should take minutes.

Most of those failures are ordinary formatting problems. An address is missing, a country is written in lower case, a phone number has letters in it or the same email appears twice. None of them needs a CRM. They can be found in Google Sheets before the file is uploaded.

This guide gives you a ready-made Apps Script that checks a contact sheet in one pass and writes a problem report. It also gives the formula versions of the same checks if you would rather not open the script editor.


What a CRM Import Checker Looks For

A pre-flight check is a set of small rules applied to every row. Each rule either passes or produces a message. The script below uses six columns and the following rules.

Column Rule Failure message
email Present, shaped like an address and no longer than 254 characters email is required, email is not valid, email is longer than 254 characters
firstName Present first name is required
lastName Present last name is required
phone If present, 7 to 15 digits after removing spaces and punctuation phone must have 7 to 15 digits
country If present, two uppercase letters country must use two uppercase letters
company No longer than 100 characters company is longer than 100 characters

One extra rule walks the whole email column and flags the second and later copies of an address. That rule catches the duplicate that a row-by-row check cannot see. The first copy is left alone, so the report points to the row you are likely to remove.

Keep the rule list short at first. A checker with twenty rules is hard to trust and harder to maintain. Add a rule when a real import has failed because of it.


The Ready-Made Apps Script

Open your contact spreadsheet, choose Extensions then Apps Script, replace the starter file with the code below and save it as CRM Import Check. Run validateCrmImport from the editor and authorise the script when Google asks. It reads the active sheet and writes a tab called Import Check.

/**
 * Checks the active sheet against import rules and writes a problem report.
 * Each rule returns null when the value passes or a message when it fails.
 */
const CRM_IMPORT_RULES = {
  email: [
    (value) => (String(value).trim() ? null : "email is required"),
    (value) => {
      const raw = String(value || "").trim();
      if (!raw) {
        return null;
      }
      return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(raw) ? null : "email is not valid";
    },
    (value) =>
      String(value).trim().length <= 254
        ? null
        : "email is longer than 254 characters",
  ],
  firstName: [(value) => (String(value).trim() ? null : "first name is required")],
  lastName: [(value) => (String(value).trim() ? null : "last name is required")],
  phone: [
    (value) => {
      const raw = String(value || "").trim();
      if (!raw) {
        return null;
      }
      const digits = raw.replace(/\D/g, "").length;
      return digits >= 7 && digits <= 15 ? null : "phone must have 7 to 15 digits";
    },
  ],
  country: [
    (value) => {
      const raw = String(value || "").trim();
      if (!raw) {
        return null;
      }
      return /^[A-Z]{2}$/.test(raw) ? null : "country must use two uppercase letters";
    },
  ],
  company: [
    (value) =>
      String(value || "").trim().length <= 100
        ? null
        : "company is longer than 100 characters",
  ],
};

function validateCrmImport() {
  const sheet = SpreadsheetApp.getActiveSheet();
  const values = sheet.getDataRange().getValues();
  if (values.length < 2) {
    throw new Error("Add a header row and at least one contact row first.");
  }
  const header = values[0].map((cell) => String(cell).trim().toLowerCase());
  const columnOf = (name) => header.indexOf(name);
  if (columnOf("email") === -1) {
    throw new Error("The first row must include an email column.");
  }
  const report = [["Row", "Column", "Value", "Problem"]];
  const emailColumn = columnOf("email");
  const emails = values
    .slice(1)
    .map((row) => String(row[emailColumn] || "").trim().toLowerCase());
  const seen = new Set();
  for (let r = 1; r < values.length; r += 1) {
    const row = values[r];
    Object.keys(CRM_IMPORT_RULES).forEach((name) => {
      const column = columnOf(name);
      if (column === -1) {
        return;
      }
      CRM_IMPORT_RULES[name].forEach((rule) => {
        const problem = rule(row[column]);
        if (problem) {
          report.push([r + 1, name, String(row[column] || ""), problem]);
        }
      });
    });
    const email = emails[r - 1];
    if (email) {
      if (seen.has(email)) {
        report.push([
          r + 1,
          "email",
          String(row[emailColumn] || ""),
          "duplicate email in this file",
        ]);
      } else {
        seen.add(email);
      }
    }
  }
  const book = SpreadsheetApp.getActiveSpreadsheet();
  let output = book.getSheetByName("Import Check");
  if (!output) {
    output = book.insertSheet("Import Check");
  }
  output.clearContents();
  output.getRange(1, 1, report.length, 4).setValues(report);
  console.log("Import check finished. Problems found: " + (report.length - 1));
}

The script uses getValues() to read the sheet in one call and setValues() to write the report in one call. That matters on a large contact list, where writing a row at a time with appendRow() is much slower. For a short list, appendRow() is simpler and gives the same result.

Rules live in the CRM_IMPORT_RULES object at the top. Each rule is a function that takes a cell value and returns either null or a message. To add a state code check, add a state key with one function under it. The row loop will pick it up when the sheet has a column with that header.

Header names are matched in lower case, so Email, email and EMAIL all work. A column that is absent is skipped rather than reported as an error, which lets you run the same script on exports with different column sets.


A Worked Example

Take a short contact sheet with six rows of data.

Row email firstName lastName phone country
2 marie@zephyrion.com Marie Curie +44 7700 900123 GB
3 isaac@orbitra.co Isaac Newton +1 415 555 0132 US
4 rosalind@helixa.io Rosalind Franklin 020 7946 0958 GB
5 bad-address Alan Turing +44 7700 900123 gb
6 marie@zephyrion.com Grace Hopper +1 415 555 0199 US
7 Ada Lovelace 123 US

The report has five problems across three rows.

Row Column Value Problem
5 email bad-address email is not valid
5 country gb country must use two uppercase letters
6 email marie@zephyrion.com duplicate email in this file
7 email email is required
7 phone 123 phone must have 7 to 15 digits

The report names the row as the spreadsheet sees it, including the header, so you can jump straight to the cell. A clean sheet produces a report with the header only and a problem count of zero.


Formula Checks Without a Script

For a one-off file, add a helper column and check the fields that usually fail. The formulas below assume the email is in column A, the phone in column B and the country in column C.

Required email:

=IF(TRIM(A2)="","email is required","")

Email format and length:

=IF(AND(TRIM(A2)<>"",NOT(REGEXMATCH(TRIM(A2),"^[^\s@]+@[^\s@]+\.[^\s@]+$"))),"email is not valid",IF(LEN(TRIM(A2))>254,"email is too long",""))

Phone digit count, ignoring spaces and punctuation:

=IF(B2="","",LET(digits,LEN(REGEXREPLACE(B2,"\D","")),IF(OR(digits<7,digits>15),"phone out of range","")))

Country code:

=IF(AND(C2<>"",NOT(REGEXMATCH(C2,"^[A-Z]{2}$"))),"country must use two uppercase letters","")

Duplicate email anywhere in the column:

=IF(AND(A2<>"",COUNTIF($A$2:$A,A2)>1),"duplicate email","")

Join the results into one message with TEXTJOIN so a filter on the helper column leaves only the bad rows:

=TEXTJOIN("; ",TRUE,D2,E2,F2,G2,H2)

The formula route is easy to inspect and good for a single import. The script route wins when the same file arrives every week, because it produces one report with no helper columns left in the working sheet.


Troubleshooting Common Failures


Where the Check Stops

A CSV pre-flight check is about file hygiene. It cannot tell you whether a picklist value exists in the target CRM, whether a company name matches an existing account or whether an address is deliverable. Those checks need CRM data or a reference service.

The duplicate rule also compares exact addresses only. A contact recorded as marie@zephyrion.com in one system and m.curie@zephyrion.com in another is two different strings to the script. For that class of problem, fuzzy matching is the right tool. The FLOOKUP and FUZZYSIM functions score near-duplicate names and addresses inside the sheet, and the email cleaning guide covers domain typos before the upload step.

Keep the two jobs separate. Use this check to stop bad rows reaching the CRM, then use matching to decide which good rows describe the same record.


Check Before You Upload

A failed CRM import is rarely a mystery. It is a missing email, a lower case country code, a short phone number or a repeated address. A short script in Google Sheets finds all four in one pass and gives you a row by row report you can fix before the upload.

Paste the script once, keep the rule list small and add a rule only when a real import has failed because of it. For a single file, the formula checks give the same answer without opening the script editor. When the same export arrives every week, the report tab is the faster workflow.


Frequently Asked Questions

What does a CRM import checker do in Google Sheets?

It reads the contact rows in a sheet and reports every row that fails a rule before upload. Common rules cover required fields, email format, phone digit count, country codes and duplicate emails.

How do I run the Apps Script validator?

Open Extensions then Apps Script, paste the script, save it and run validateCrmImport. Authorise the script when asked, then open the Import Check tab for the problem report.

Can I check a CSV with formulas instead of Apps Script?

Yes. REGEXMATCH, LEN, COUNTIF and TEXTJOIN cover required fields, format checks, length limits and duplicates. A formula check is useful for a one-off list, while the script reports every problem in one pass.

Why does a valid phone number fail the digit check?

The check counts digits after removing spaces, brackets and dashes. An extension, a country code stored separately or a number with letters left in it will change the count and produce a failure.

Will this replace CRM validation at upload?

No. The CRM still checks its own picklists, object rules and permissions. The sheet check catches the ordinary formatting errors before upload, so the import fails less often and is easier to fix.


You Might Also Like