Functional Weave
Code in Python

form.address@1.0.0

impl/rust/validate_address.rs

5,995 bytes · the Rust implementation · view raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

use super::form_address_address_format::{is_uk_family, lookup_country, trim_ascii, upper_ascii};  ← addressFormat, another function of this group · built into the same file, even by a slim install
use super::funejson::Value;  ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one
use super::text_pattern_match::matches_pattern;  ← from text.pattern-match ^1.0.0 · built alongside by fune
use super::validation_uk_postcode::validate_uk_postcode;  ← from validation.uk-postcode ^2.0.0 · built alongside by fune

const MAX_LENGTH: usize = 100;

// "Enter postcode", but "Enter ZIP code" and "Enter Eircode": only the two
// ordinary labels are common nouns.
fn in_sentence(label: &str) -> String {
    if label == "Postcode" || label == "Postal code" {
        label.to_ascii_lowercase()
    } else {
        label.to_string()
    }
}

// Without a known format: 1 to 12 letters, digits, spaces and hyphens.
fn plausible_postcode(value: &str) -> bool {
    (1..=12).contains(&value.chars().count())
        && value.chars().all(|ch| ch.is_ascii_uppercase() || ch.is_ascii_digit() || ch == ' ' || ch == '-')
}

fn error(field: &str, message: String) -> AddressError {
    AddressError { field: field.to_string(), message }
}

/// A postal address checked field by field: the GOV.UK address pattern for
/// the UK, the country's own postcode format and labels elsewhere. Never
/// panics: an unknown country is the country field's error.
pub fn validate_address(address: &Address) -> AddressCheck {
    let mut errors: Vec<AddressError> = Vec::new();
    let row = lookup_country(&address.country);
    let region_label = row.map(|r| r.region_label).unwrap_or("Region");
    let postcode_label = row.map(|r| r.postcode_label).unwrap_or("Postal code");
    // Unicode code points, as in the other languages.
    let length = |s: &str| s.chars().count();

    let line1 = trim_ascii(&address.line1);
    if line1.is_empty() {
        errors.push(error("line1", "Enter address line 1, typically the building and street".to_string()));
    } else if length(line1) > MAX_LENGTH {
        errors.push(error("line1", format!("Address line 1 must be {} characters or less", MAX_LENGTH)));
    }

    let line2 = trim_ascii(address.line2.as_deref().unwrap_or(""));
    if length(line2) > MAX_LENGTH {
        errors.push(error("line2", format!("Address line 2 must be {} characters or less", MAX_LENGTH)));
    }

    let town = trim_ascii(&address.town);
    if town.is_empty() {
        errors.push(error("town", "Enter town or city".to_string()));
    } else if length(town) > MAX_LENGTH {
        errors.push(error("town", format!("Town or city must be {} characters or less", MAX_LENGTH)));
    }

    let region = trim_ascii(address.region.as_deref().unwrap_or(""));
    if length(region) > MAX_LENGTH {
        errors.push(error("region", format!("{} must be {} characters or less", region_label, MAX_LENGTH)));
    }

    let typed = trim_ascii(address.postcode.as_deref().unwrap_or(""));
    let mut postcode: Option<String> = None;
    if typed.is_empty() {
        if row.map(|r| r.postcode_required).unwrap_or(false) {
            errors.push(error("postcode", format!("Enter {}", in_sentence(postcode_label))));
        }
    } else if row.map(|r| is_uk_family(r.code)).unwrap_or(false) {
        let uk = validate_uk_postcode(typed);
        if uk.valid {
            postcode = uk.normalised;
        } else {
            errors.push(error("postcode", format!("Enter a real {}", in_sentence(postcode_label))));
        }
    } else {
        let upper = upper_ascii(typed);
        let ok = match row.and_then(|r| r.postcode_pattern) {
            Some(pattern) => matches_pattern(pattern, &upper),
            None => plausible_postcode(&upper),
        };
        if ok {
            postcode = Some(upper);
        } else {
            errors.push(error("postcode", format!("Enter a real {}", in_sentence(postcode_label))));
        }
    }

    let row = match row {
        Some(row) if errors.is_empty() => row,
        _ => {
            if row.is_none() {
                errors.push(error("country", "Select a country".to_string()));
            }
            return AddressCheck { valid: false, address: None, errors };
        }
    };
    let optional = |s: &str| if s.is_empty() { None } else { Some(s.to_string()) };
    AddressCheck {
        valid: true,
        address: Some(Address {
            line1: line1.to_string(),
            line2: optional(line2),
            town: town.to_string(),
            region: optional(region),
            postcode,
            country: row.code.to_string(),
        }),
        errors: Vec::new(),
    }
}

pub fn address_from_value(v: &Value) -> Address {
    let text = |key: &str| match v.get(key) {
        Value::Str(s) => s.clone(),
        _ => panic!("address.{} must be a string", key),
    };
    let optional = |key: &str| match v.get(key) {
        Value::Str(s) => Some(s.clone()),
        _ => None,
    };
    Address {
        line1: text("line1"),
        line2: optional("line2"),
        town: text("town"),
        region: optional("region"),
        postcode: optional("postcode"),
        country: text("country"),
    }
}

pub fn address_to_value(a: &Address) -> Value {
    let text = |v: &Option<String>| v.as_deref().map(Value::str).unwrap_or(Value::Null);
    Value::obj(vec![
        ("line1", Value::str(&a.line1)),
        ("line2", text(&a.line2)),
        ("town", Value::str(&a.town)),
        ("region", text(&a.region)),
        ("postcode", text(&a.postcode)),
        ("country", Value::str(&a.country)),
    ])
}

pub fn address_check_to_value(check: &AddressCheck) -> Value {
    Value::obj(vec![
        ("valid", Value::Bool(check.valid)),
        ("address", check.address.as_ref().map(address_to_value).unwrap_or(Value::Null)),
        (
            "errors",
            Value::Arr(
                check
                    .errors
                    .iter()
                    .map(|e| Value::obj(vec![("field", Value::str(&e.field)), ("message", Value::str(&e.message))]))
                    .collect(),
            ),
        ),
    ])
}

pub fn fune_vector(args: &[Value]) -> Value {
    address_check_to_value(&validate_address(&address_from_value(&args[0])))
}