Untitled

mail@pastecode.io avatar
unknown
typescript
a year ago
2.2 kB
2
Indexable

export class AddressValidator {
  #address: Address;

  constructor(address: Address) {
    this.#address = address;
  }

  public isValidId(): AddressValidator {
    const id = this.#address.get.id;
    if (id === null || id === undefined || id === "") {
      AddressError.idIsRequired().dispatch();
    }
    return this;
  }

  public isValidLocal(): AddressValidator {
    const local = this.#address.get.local;
    if (local.trim().length < 10) {
      AddressError.invalidLocal().dispatch();
    }
    return this;
  }

  public isValidAddress(): AddressValidator {
    const address = this.#address.get.address;
    if (address.trim().length < 15) {
      AddressError.invalidAddress().dispatch();
    }
    return this;
  }

  public isValidNeighbourhood(): AddressValidator {
    const neighbourhood = this.#address.get.neighbourhood;
    if (neighbourhood.trim().length < 5) {
      AddressError.invalidNeighbourhood().dispatch();
    }
    return this;
  }

  public isValidPostalCode(): AddressValidator {
    const postalCodeBr = /^\d{5}-?\d{3}$/;
    if (!postalCodeBr.test(this.#address.get.postalCode)) {
      AddressError.invalidPostalCode().dispatch();
    }
    return this;
  }

  public isValidCity(): AddressValidator {
    const city = this.#address.get.city;
    if (city.length <= 0 || !city) {
      AddressError.cityIsRiquired().dispatch();
    }
    return this;
  }

  public isValidState(): AddressValidator {
    const state = this.#address.get.state;
    if (state.length !== 2) {
      AddressError.invalidState().dispatch();
    }
    return this;
  }

  public isValidLatitude(): AddressValidator {
    const latitude = this.#address.get.latitude;
    if (latitude) {
      if (typeof latitude !== 'number' || latitude < -90 || latitude > 90) {
        AddressError.invalidLatitude().dispatch();
      }
    }
    return this;
  }

  public isValidLongitude(): AddressValidator {
    const longitude = this.#address.get.longitude;
    if (longitude) {
      if (typeof longitude !== 'number' || longitude < -180 || longitude > 180) {
        AddressError.invalidLongitude().dispatch();
      }
    }
    return this;
  }
}