Config-Driven CSV Validator with Name Overlap Check
StringsModel answerLast updated
Write a configurable validator that flags missing fields, length violations, banned words, and low name-word overlap across CSV vendor rows.
A vendor-onboarding pipeline receives a CSV export: a header line specifies the column names, and every subsequent line describes one vendor. You need to build a validator that inspects each record against a rule set provided as configuration and reports which rules that record violates. No rule details (column names, required columns, length bounds, banned vocabulary, the columns to compare for naming consistency, how strict that comparison is) may be baked into the code — all of it arrives via the config, and you should describe the config shape you assume.
vendor_id,vendor_name,legal_name,notes
1,Acme Robotics,Acme Robotics LLC,Primary supplier
2,,Bright Labs LLC,Missing display name
3, ACME Robotics ,acme robotics llc,Spacing and case only
4,Zed,Zed Logistics Inc,Display name too short
Function Signature
def validate_vendor_records(csv_text: str, config: dict) -> list[dict]:
Rules
- The first line is the header; each following line is one record. A value can contain commas when quoted, so use a proper CSV parser — never
split(","). - The validator is read-only with respect to records: it reports problems and never rewrites, sorts, removes, or merges rows.
configprovides:required_fields,length_limits(per-field(min, max)measured after trimming),forbidden_words(whole-word, case-insensitive, checked on every field),overlap_fields(a pair of columns to compare),ignored_words(removed before comparison, e.g.llc,inc), andmin_overlap_ratio.- A field is missing when, after trimming, it is empty or whitespace only.
- Overlap check: for each of the two configured columns, lowercase the value, strip punctuation, tokenize on whitespace, remove
ignored_words, then compute the Jaccard ratio|intersection| / |union|between the two token sets. If both columns are non-empty and the ratio falls belowmin_overlap_ratio, emit"name_mismatch". - Every record appears in the output, in input order, even when its issue list is empty.
Part 1 — Per-field checks
For every record, verify each required_fields entry for presence, verify each length_limits entry for range, and scan every field value for any forbidden_words.
Part 2 — Cross-field overlap
Using overlap_fields and ignored_words, compute the Jaccard ratio as described and flag records whose two name columns don't look related enough.
Example
config = {
"required_fields": ["vendor_id", "vendor_name", "legal_name"],
"length_limits": {"vendor_name": (4, 80), "legal_name": (4, 120)},
"forbidden_words": ["test", "dummy"],
"overlap_fields": ("vendor_name", "legal_name"),
"ignored_words": {"inc", "llc", "ltd", "co", "corp", "company", "the"},
"min_overlap_ratio": 0.5,
}
# Row 2 (missing vendor_name) -> {"row": 2, "issues": ["missing:vendor_name"]}
# Row 4 (vendor_name "Zed", length 3 < min 4) -> {"row": 4, "issues": ["length:vendor_name"]}
Constraints
- Up to
10^4rows and50columns. - Field values are printable text; forbidden words and ignored words match case-insensitively as whole words only.
Hints
Hint 1
Use csv.DictReader over io.StringIO so quoted commas are handled and columns missing from short rows come back as None.
Hint 2
Match banned words with a word-boundary regex (\b word \b, re.IGNORECASE) so 'test' doesn't fire inside 'attestation'.
Hint 3
Normalize both name columns identically — lowercase, non-alphanumerics to spaces, split, subtract ignored words — before computing Jaccard on the two sets.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task decomposes into two independent passes over each record, sharing one text-normalization helper for the second pass.
- Parse with
csv.DictReader(wrapped inio.StringIO) so quoting is respected and each record arrives as acolumn -> valuemapping. - For each record, run all per-field checks (
required_fields,length_limits,forbidden_words) and accumulate every failure — never stop at the first, because the spec wants the complete failing-rule list per record. - Run the overlap check as a separate second step on the same record, using a shared normalization helper.
- Emit exactly one result per input record, in order, whether or not it has issues.
Missing fields. A value is missing when value.strip() == "". This also handles columns absent from a shorter row: DictReader fills them with None, and (value or "") safely converts that to empty string.
Length limits. Only validate non-empty trimmed values. "Missing" and "too short" are distinct rules a reviewer can toggle independently; an empty value already receives a missing: flag, so stacking length: on top would be redundant noise.
Forbidden words. Use a whole-word regex, \bword\b with re.IGNORECASE, rather than a substring test, so "test" does not fire inside "testing" or "attestation". Scan every field in the record, not just the name columns — banned content can hide in notes.
Overlap. Normalize each configured column the same way: lowercase, replace every non-alphanumeric character with a space, split on whitespace, and discard tokens in ignored_words. Compare the resulting sets by Jaccard ratio. If either set is empty after normalization, treat it as "insufficient information" rather than an automatic mismatch — a missing: or length: flag already covers that record, and a ratio over an empty set would be undefined or spuriously 0.
Edge cases
- Whitespace-only values trim to empty and are flagged
missing:. - A banned word appearing inside a longer legitimate word must not match — this is why word boundaries matter.
- Both overlap columns present but sharing zero tokens after ignored-word removal: ratio is 0, flagged
name_mismatchwhenevermin_overlap_ratio > 0. - A record with several simultaneous problems: all issues appear, not just the first.
- Missing
overlap_fieldsor emptyforbidden_wordsin config: those checks are simply skipped (treat optional keys as absent).
Complexity
Parsing is O(total CSV size). Per record, each check is linear in the number of configured fields/words, and the overlap check is linear in the length of the two compared strings. Overall O(total input size × number of configured checks), effectively linear for realistic configurations.
Reference implementation
import csv
import io
import re
def normalize_words(text, ignored_words):
text = text.lower()
text = re.sub(r"[^a-z0-9\s]", " ", text)
return {w for w in text.split() if w and w not in ignored_words}
def validate_vendor_records(csv_text, config):
required_fields = config["required_fields"]
length_limits = config.get("length_limits", {})
forbidden_words = [w.lower() for w in config.get("forbidden_words", [])]
overlap_fields = config.get("overlap_fields")
ignored_words = {w.lower() for w in config.get("ignored_words", set())}
min_overlap_ratio = config.get("min_overlap_ratio", 0.0)
reader = csv.DictReader(io.StringIO(csv_text))
results = []
for row_num, row in enumerate(reader, start=1):
issues = []
# Part 1: per-field checks
for field in required_fields:
if (row.get(field) or "").strip() == "":
issues.append(f"missing:{field}")
for field, (min_len, max_len) in length_limits.items():
value = (row.get(field) or "").strip()
if value and not (min_len <= len(value) <= max_len):
issues.append(f"length:{field}")
for field, value in row.items():
value = value or ""
for word in forbidden_words:
if re.search(rf"\b{re.escape(word)}\b", value, flags=re.IGNORECASE):
issues.append(f"forbidden_word:{field}:{word}")
# Part 2: cross-field overlap
if overlap_fields:
f1, f2 = overlap_fields
v1 = (row.get(f1) or "").strip()
v2 = (row.get(f2) or "").strip()
if v1 and v2:
w1 = normalize_words(v1, ignored_words)
w2 = normalize_words(v2, ignored_words)
union = w1 | w2
ratio = (len(w1 & w2) / len(union)) if union else 1.0
if ratio < min_overlap_ratio:
issues.append("name_mismatch")
results.append({"row": row_num, "issues": issues})
return results
This reproduces the worked example: rows 1 and 3 (same vendor, casing/spacing differences only) come back clean; row 2 is flagged missing:vendor_name; row 4 is flagged length:vendor_name.