[u] add validation

This commit is contained in:
Grisha 2024-09-17 21:48:21 +03:00
parent 6c31d999c9
commit 35c1533ab0

View file

@ -3,6 +3,8 @@ package org.schabi.newpipe.settings;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.os.Bundle; import android.os.Bundle;
import android.util.Log; import android.util.Log;
import android.util.Patterns;
import android.widget.Toast;
import androidx.preference.Preference; import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat; import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.SwitchPreferenceCompat; import androidx.preference.SwitchPreferenceCompat;
@ -52,6 +54,12 @@ public class ProxySettingsFragment extends PreferenceFragmentCompat {
assert proxyAddressPref != null; assert proxyAddressPref != null;
proxyAddressPref.setOnPreferenceChangeListener((preference, newValue) -> { proxyAddressPref.setOnPreferenceChangeListener((preference, newValue) -> {
// Валидация IP-адреса
if (!isValidIpAddress(newValue.toString())) {
Toast.makeText(getContext(),
getString(R.string.invalid_ip_address), Toast.LENGTH_SHORT).show();
return false; // Не сохраняем изменение
}
Log.d("ProxySettings", "Read proxy_address_key: " + newValue); Log.d("ProxySettings", "Read proxy_address_key: " + newValue);
// Сохраняем новое значение IP-адреса // Сохраняем новое значение IP-адреса
sharedPreferences.edit().putString( sharedPreferences.edit().putString(
@ -67,6 +75,12 @@ public class ProxySettingsFragment extends PreferenceFragmentCompat {
assert proxyPortPref != null; assert proxyPortPref != null;
proxyPortPref.setOnPreferenceChangeListener((preference, newValue) -> { proxyPortPref.setOnPreferenceChangeListener((preference, newValue) -> {
// Валидация порта
if (!isValidPort(newValue.toString())) {
Toast.makeText(getContext(),
getString(R.string.invalid_port), Toast.LENGTH_SHORT).show();
return false; // Не сохраняем изменение
}
Log.d("ProxySettings", "Read proxy_port_key: " + newValue); Log.d("ProxySettings", "Read proxy_port_key: " + newValue);
// Сохраняем новое значение порта // Сохраняем новое значение порта
sharedPreferences.edit().putString( sharedPreferences.edit().putString(
@ -74,6 +88,18 @@ public class ProxySettingsFragment extends PreferenceFragmentCompat {
newValue.toString()).apply(); newValue.toString()).apply();
return true; return true;
}); });
// Метод для валидации IP-адреса
public boolean isValidIpAddress(final String ipAddress) {
return Patterns.IP_ADDRESS.matcher(ipAddress).matches();
}
// Метод для валидации порта
public boolean isValidPort(final String port) {
try {
final int portNumber = Integer.parseInt(port);
return portNumber >= 1 && portNumber <= 65535;
} catch (final NumberFormatException e) {
return false;
}
} }
} }