Answer the question
In order to leave comments, you need to log in
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'));
}
}
Also, will be good to validate the API key and the city name by the API request.
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;
}
}
validateForm
. Please tell me how to do it? Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question