Validation and Sanitization are two terms are often confused and/or misused by beginning developers. So what is the difference between sanitization and validation? Well let’s start with validation, as it happens before sanitization. Simply put, validation is verifying that the data being submitted conforms to a rule or set of rules you (the developer) set for a particular input field. This could mean something as simple as verifying that a form field wasn’t left blank, or it could mean using a complicated regex pattern to verify that an email or phone number is valid.
Now that we have that out of the way, let’s talk about sanitization. Whereas validation requires user input to conform to a certain rule or rules put forth by the developer, sanitization only cares about removing code, text or characters from data that’s not allowed.
Sanitizing and escaping data are two different things. Sanitization removes code from data whereas escaping escapes the language defined keywords or characters in the data so that they are displayed not executed.
Examples of validating, escaping and sanitizing:
- Escaping: When you are sending a message using Facebook the message is escaped so that if you are sending some code then its just displayed not executed
- Validating: While filling up a registration form your email address and password are validated. If these don’t follow the format then a validation error is displayed.
- Sanitization: While viewing an HTML email in Gmail its sanitized i.e.,
<style>tag is removed so that Gmail’s style is not overwritten.
register_setting function of settings API saves the value attribute on form submission directly into the database. We can also sanitize, validate or escape the value based on our choice. This
register_setting function takes a third argument which is a callback, this callback is fired before it saves the settings into the database.
Let’s take advantage of the callback to sanitize text input field data. Here is an example code
add_settings_section("section", "Section", null, "demo");
add_settings_field("demo-text", "Demo Text", "demo_text_display", "demo", "section");
register_setting("section", "demo-text", "handle_sanitization_validation_escaping_text");
$option = sanitize_text_field($option);
<input type="text" name="demo-text" value="<?php echo get_option('demo-text'); ?>" />
<form method="post" action="options.php">
add_submenu_page("options-general.php", "Demo", "Demo", "manage_options", "demo", "demo_page");