shelving
Version:
Toolkit for using data in JavaScript.
27 lines (26 loc) • 1.29 kB
JavaScript
import { COUNTRIES, getCountry } from "../util/geo.js";
import { isProp } from "../util/object.js";
import { ChoiceSchema } from "./ChoiceSchema.js";
import { NULLABLE } from "./NullableSchema.js";
/** Schema that validates an ISO country code. */
export class CountrySchema extends ChoiceSchema {
defaultValue;
constructor({ one = "country", title = "Country", value = "detect", ...options } = {}) {
super({ one, title, options: COUNTRIES, value: value === "detect" ? "GB" : value, ...options });
this.defaultValue = value;
}
validate(unsafeValue = this.defaultValue) {
const country = getCountry(unsafeValue);
if (country)
return super.validate(country);
if (unsafeValue === undefined || unsafeValue === null || unsafeValue === "" || unsafeValue === "detect")
throw "Required";
if (typeof unsafeValue === "string" && isProp(COUNTRIES, unsafeValue.toUpperCase()))
return super.validate(unsafeValue.toUpperCase());
return super.validate(unsafeValue);
}
}
/** Valid country code, e.g. `GB` (required because falsy values are invalid). */
export const COUNTRY = new CountrySchema({});
/** Valid country code, e.g. `GB`, or `null` */
export const NULLABLE_COUNTRY = NULLABLE(COUNTRY);