Parse and Validate Business Registration CSV Records
StringsAuto-graded · 21 test casesLast updated
Tests multi-rule sequential validation over CSV rows: field presence, tax ID format normalization, and fuzzy owner name matching via token overlap.
Parse and Validate Business Registration CSV Records
A business registry system receives CSV exports of company onboarding submissions. Each row contains five fields describing a business and its ownership. Your job is to parse the CSV and run a series of checks against each record, returning a structured validation report.
Write a function validate_business_records(csv_data: str) -> list[dict] that takes the raw CSV text and returns one result entry per data row.
Input Format
csv_data is a multi-line string. The first line is always the header:
record_id,business_name,tax_id,legal_owner_name,submitted_owner_name
Any field may have leading or trailing whitespace; strip it before processing. Fields do not contain commas or quoted values.
Validation Rules
Apply the following checks to each row, in this order:
Rule 1 — Required Fields
All five fields must be non-empty after stripping whitespace. If one or more are empty, add "MISSING_REQUIRED_FIELD" to the error list exactly once, then continue checking the remaining rules against whichever fields are present.
Rule 2 — Tax ID Format
Only run this check when tax_id is non-empty. Remove all hyphens (-) and spaces from tax_id, then verify that the result is exactly 9 characters long and every character is an ASCII digit (0–9). Any other character, including Unicode digit-like symbols, is invalid. If the check fails, add "INVALID_TAX_ID".
Rule 3 — Owner Name Match
Only run this check when both legal_owner_name and submitted_owner_name are non-empty. Normalize each name by:
- Converting every character to lowercase.
- Replacing every character that is not a letter, digit, or space with a space.
- Splitting on whitespace to produce a set of unique tokens.
Let S be the token set of submitted_owner_name and L be the token set of legal_owner_name.
The names are considered a match when both of the following hold:
- At least one token is shared:
|S ∩ L| ≥ 1 - The shared tokens cover at least half of the submitted tokens:
|S ∩ L| / |S| ≥ 0.5
If either condition fails, or if S is empty (e.g., the name consists entirely of symbols), add "OWNER_NAME_MISMATCH".
A record can accumulate errors from multiple rules. Errors always appear in the order listed above (Rule 1 → Rule 2 → Rule 3).
Output Format
Return a list of dictionaries, one per data row, in the same order they appear in the input:
[
{
"record_id": str, # trimmed value, or "" if the field was absent
"is_valid": bool, # True only when errors is empty
"errors": list[str] # error codes in rule order
},
...
]
Constraints
- The input contains between 1 and 10,001 lines (1 header + up to 10,000 data rows).
- Fields do not contain commas or escaped quotes.
- A completely blank line in the CSV body is treated as a row of empty fields and will produce a
"MISSING_REQUIRED_FIELD"error withrecord_id: "". - Extra columns beyond the fifth are ignored; missing trailing columns are treated as empty strings.
Examples
Example 1
Input: validate_business_records('record_id,business_name,tax_id,legal_owner_name,submitted_owner_name\nrec_1,Acme Corp,12-3456789,Jane Doe,Jane Doe\nrec_2,Beta LLC,99-999,Robert Smith,Bob Smith\nrec_3,Gamma Inc,11-2233445,Alice M. Walker,Alice Walker\n')
Output: [{'record_id': 'rec_1', 'is_valid': True, 'errors': []}, {'record_id': 'rec_2', 'is_valid': False, 'errors': ['INVALID_TAX_ID']}, {'record_id': 'rec_3', 'is_valid': True, 'errors': []}]
Example 2
Input: validate_business_records('record_id,business_name,tax_id,legal_owner_name,submitted_owner_name\n r1 , Acme Corp , 123 456 789 , Jane Doe , Jane Doe \nr2,Beta LLC,12345678A,Robert Smith,Robert Jones\n')
Output: [{'record_id': 'r1', 'is_valid': True, 'errors': []}, {'record_id': 'r2', 'is_valid': False, 'errors': ['INVALID_TAX_ID']}]
Example 3
Input: validate_business_records('record_id,business_name,tax_id,legal_owner_name,submitted_owner_name\n')
Output: []
Hints
Hint 1
Start by using Python's csv.reader (wrapped around io.StringIO) to parse the rows — it handles edge cases like blank lines and short rows more cleanly than splitting on commas manually. Pad each parsed row to exactly five fields with empty strings.
Hint 2
For the tax ID check, strip hyphens and spaces first, then verify length and character set. Use a character-by-character comparison against '0'–'9' rather than str.isdigit(), which accepts non-ASCII digit characters.
Hint 3
For the name match, replace non-alphanumeric characters with spaces (not empty string) before splitting — this ensures punctuation like the period in 'Alice M.' or the apostrophe in 'O'Brien' correctly separates tokens. Then measure the overlap ratio against the size of the *submitted* token set.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem is a straightforward sequential pipeline: for each row, run three independent checks in a fixed order and collect any errors. Nothing about one row affects another, so no cross-row state is needed.
Parsing
csv.reader wrapped around io.StringIO handles the CSV correctly. It deals with blank lines, short rows (missing trailing fields), and strips nothing — we do the whitespace stripping ourselves by iterating over indices 0–4 and calling .strip(). If a row has fewer than five columns, the missing ones default to "". Extra columns are silently ignored by taking only the first five.
next(reader, None) skips the header and does nothing on empty input.
Rule 1 — Required fields
After stripping, check whether any of the five fields is an empty string. If so, append "MISSING_REQUIRED_FIELD" exactly once. The check does not short-circuit: rules 2 and 3 still run if their specific fields are non-empty. A row missing only business_name, for example, can still fail Rule 2 if its tax_id is malformed.
Rule 2 — Tax ID
Strip - and from tax_id, then verify:
len(cleaned) == 9- every character satisfies
"0" <= ch <= "9"
The character comparison is deliberately stricter than str.isdigit(). Python's isdigit() returns True for Unicode characters like ² (superscript two) and Arabic-Indic digits, none of which belong in a tax ID. The explicit ASCII range comparison avoids that ambiguity.
Rule 3 — Owner name match
Punctuation is replaced with a space, not deleted. This matters: "Alice M." becomes "alice m " → {"alice", "m"}, not {"alicem"}. The normalization loop replaces every non-alphanumeric, non-space character with " ", lowercases the rest, then splits on whitespace. Splitting a string that is all spaces produces an empty list, so set() is empty — this correctly triggers OWNER_NAME_MISMATCH and avoids a division-by-zero error.
The overlap ratio is measured against the submitted token set S, not the legal set. This means a legal name with extra middle initials or titles does not penalize the submitted name. For example, with legal = "Alice M. Walker" → L = {alice, m, walker} and submitted = "Alice Walker" → S = {alice, walker}: overlap is {alice, walker}, ratio is 2/2 = 1.0 — a match.
The threshold ≥ 0.5 is inclusive, so a two-token submitted name with exactly one match (ratio = 0.5) passes.
Why errors stay in rule order
Each rule appends at most one error code to the same errors list. Since the three if blocks execute in order 1 → 2 → 3, the resulting list is always sorted by rule number, satisfying the spec's ordering requirement.
Correctness note on the sample
For rec_2 (tax_id = "99-999", legal = "Robert Smith", submitted = "Bob Smith"): the tax ID is invalid (5 digits after stripping). The name check gives S = {bob, smith}, L = {robert, smith}, overlap = {smith}, ratio = 1/2 = 0.5 — this passes Rule 3. So the only error is "INVALID_TAX_ID".
Complexity
- Time: O(N) in total input characters. Each character is visited a constant number of times across parsing, stripping, and normalization. Set intersection is linear in token count.
- Space: O(R) for the result list over R rows. Per-row allocations (the two token sets) are O(row length) and are discarded after each iteration.
Edge cases
| Scenario | Behavior |
|---|---|
| Header-only or empty string | next(reader, None) is safe; returns [] |
| Trailing newline | No extra row produced |
| Blank line in body | Five empty fields → record_id: "", MISSING_REQUIRED_FIELD |
Tax ID with internal spaces ("123 456 789") | Valid after stripping spaces |
Tax ID with letters ("12345678A") | INVALID_TAX_ID |
Repeated words in name ("Jane Jane") | Collapses to {jane}; ratio still computed correctly |
Name made entirely of symbols ("...") | S = set() → OWNER_NAME_MISMATCH |
Mixed case or punctuation ("JANE-DOE" vs "jane doe") | Both normalize to {jane, doe}; match |
Reference solution
import csv
import io
from typing import List, Dict, Any
def validate_business_records(csv_data: str) -> List[Dict[str, Any]]:
reader = csv.reader(io.StringIO(csv_data))
next(reader, None) # consume header; safe on empty input
results = []
for row in reader:
# Pad or truncate to exactly 5 trimmed fields
fields = [(row[i].strip() if i < len(row) else "") for i in range(5)]
record_id, business_name, tax_id, legal_owner, submitted_owner = fields
errors = []
# Rule 1: all five fields must be non-empty
if any(not field for field in fields):
errors.append("MISSING_REQUIRED_FIELD")
# Rule 2: tax ID must be exactly 9 ASCII digits after removing hyphens/spaces
if tax_id:
cleaned = tax_id.replace("-", "").replace(" ", "")
if len(cleaned) != 9 or not all("0" <= ch <= "9" for ch in cleaned):
errors.append("INVALID_TAX_ID")
# Rule 3: token-overlap owner name match
if legal_owner and submitted_owner:
def tokenize(name: str):
normalized = "".join(
ch.lower() if (ch.isalnum() or ch == " ") else " "
for ch in name
)
return set(normalized.split())
legal_tokens = tokenize(legal_owner)
submitted_tokens = tokenize(submitted_owner)
overlap = legal_tokens & submitted_tokens
if (
not submitted_tokens
or len(overlap) == 0
or len(overlap) / len(submitted_tokens) < 0.5
):
errors.append("OWNER_NAME_MISMATCH")
results.append({
"record_id": record_id,
"is_valid": not errors,
"errors": errors,
})
return results