How to validate settings API?
-
As far as I can see there is no proper way to validate the settings API.
The codex says that it should be validated by attaching a function for each field on the register_setting sanitize callback.
However, if validation fails and I add an error there is no way to stop a value from being saved. If I return no value then an empty value is saved to the database overwriting the previous value.
My understanding of validation is that if it fails no data should be saved.
I have read several tutorials and cannot find any examples that stop any value being saved when validation fails.
Is this a shortcoming of the settings api or am I just doing it wrong?
for instance lets say I don’t want a field to have any numbers in it. This sanitize function will overwrite the previous data with a blank entry if there are any numbers. The old value is not in scope of the sanitize callback and I cannot see a documented way to break operation and stop it being saved.
function test_api_opt_validate($data) { if (preg_match('#[0-9]#',$data)){ add_settings_error( 'hasNumberError', 'validationError', 'This field may not contain numbers', 'error'); }else{ return sanitize_text_field($data); } }
The topic ‘How to validate settings API?’ is closed to new replies.