A
A
aleksandrkotov2022-04-11 04:30:27
Drupal
aleksandrkotov, 2022-04-11 04:30:27

Validate the API key and the city name by the API?

I created a custom module where I display weather in a block using data from https://openweathermap.org/
The code for this block:
https://phpsandbox.io/n/sweet-forest-1lew-1wmof

I also have a WeatherForm file. php with a form that adds a city and an API key to the configuration to display the weather.

I needed to add form validation:
1. fields must not be empty
2. City name must not contain numbers

I did it like this:

public function validateForm(array &$form, FormStateInterface $form_state) {
    $pattern = '/[0-9]/';

    if (empty($form_state->getValue('weather_city'))) {
      $form_state->setErrorByName('weather_city', $this->t('Fields should not be empty'));
    }
    if (preg_match($pattern, $form_state->getValue('weather_city'))) {
      $form_state->setErrorByName('weather_city', $this->t('City name should not contain numbers'));
    }
  }

But I got this remark after code review:

Also, will be good to validate the API key and the city name by the API request.


I found an example how to implement this:

public function validateWeatherData(string $city_name, $api_key):bool {
  try {
    $url = "https://api.openweather.org/data/2.5/weather?q=$city_name&appid=$api_key";
    $response = $this->client->request('GET', $url);
    if ($response->getStatusCode() != 200) {
      throw new \Exception('Failed to retrieve data.');
    }
    $reg_ex = "#^[A-Za-z-]=$#";
    return preg_match($reg_ex, $city_name);
  }
  catch (GuzzleException $e) {
    return FALSE;
  }
}


But I don't know how to integrate the example code into my validateForm. Please tell me how to do it?
All my form code:
https://phpsandbox.io/n/spring-mountain-gdnn-emozx

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question