This is a pretty basic solution. First I am assuming that you are not saving the data/form, and just returning to the same page.. In your $formContent
you would do something like this.
<?php
$formContent="
....
<tr>
<th><label for="email">Förnamn*</label></th>
<td><input name="first_name" id="first_name" value="" class="regular-text" . $class_errors['first_name'] . '" type="text">'
. ( array_key_exists( 'first_name', $class_errors ) ? "<br/>You must enter your first name." : "" ) . '</td>
</tr>";
If you wanted to access the errors on the form itself, I would personally recommend doing the error checking through JavaScript. This way, you can actually prevent the page from submitting, rather than submitting, cancelling, and redirecting back. With jQuery, it would be something like:
$('form').submit(function(event){
var $form = $(this);
// if any empty fields with the required class are found
if ($form.find('input.required:empty').length) {
event.preventDefault(); // cancel form submission
$form.find('input.required:empty').after('<p class="error">This field is required');
}
});
Obviously you could customize each field’s message by reading the label attached to that input, or putting individual checks on each field. You can also work in some custom validation here, like Phone number validation, email, etc.
That’s my preferred method.
For the PHP side, you should be able to store your error classes either on a class variable, or a global variable. Since the post.php
page points back to itself, there is no redirection between your form submission checking, and re-rendering the page. You should be able to store the errors in a class variable and use it within both functions.
Very high level:
class myFormStuff {
protected $error_classes;
// happens first, on init most likely
function checkFrontEndRegistration(){
$this->error_classes['first_name'] = "Dude, where's your name at?";
}
// Happens way later in the page reload, when rendering the form
function frontEndRegistration() {
if ( array_key_exists( 'first_name', $this->error_classes ) ) {
echo '<p class="error">' . $this->error_classes['first_name'] . '</p>';
}
}
}