Form Validation

How to validate

Strong server-side validation is one of the main reasons to use HazzelForms. $form->validate() validates all the fields. If a field is blank or an entry is invalid, field-specific errors will be displayed and the form tag contains a class has-error.

if($form->validate()){
	 // Save zone: This code is only executed when all your fields are valid.
}

Success message / redirect

Within the valid section you can transmitt the received data (please see "Data Processing") and do other stuff like this:

if($form->validate()){
	// redirect to success page. make sure to run this before you output any html
	header('Location: https://www.example.com/');
	exit;
}

You can also place this snipped anywhere on your page after $form->validate() is executed

if($form->isValid()){
	// show a success message (hide the form with CSS when it contains the class "submitted")
	echo "Form sent, thank you!";
}
Do not use the negation !$form->isValid() as it will return true even if the form has not yet been sent.
If you want to check only for errors, use the contrary function below:
if($form->hasError()){
	// do something in case the form is not valid
}

Validation techniques

Browser-Side validation

Modern browsers validate certain content even before submitting the form. When initializing HazzelForms, this behavior can be disabled if desired:

// Disable form validation by browsers
$form = new HazzelForms\HazzelForm( ['novalidate' => true] );

Regular Expressions

If necessary, additional field-specific regular expression can be provided, with which the entries should be matched.

// Text field example with regular expression for european article number (EAN)
$form->addField('EAN', 'text', ['regex' => '^(?<=\s)\d{13}(?=\s)$']);

CSRF Prevention

Whenever HazzelForms is used within a running PHP-Session (after session_start()), a Cross Site Request Forgery (CSRF) Token is automatically generated and added to the $_SESSION array.
The CSRF token is integrated into the form as a hidden input field.

SQL Injection & Cross site scripting (XSS)

Make sure to correctly handle and encode form entries to prevent SQL injections and XSS attempts.
HazzelForms does not sanitize the transmitted data!