Creating a custom validator (advanced)

Before adding a new validator you should take a look at the files in the folder quform/lib/Quform/Validator/. You will find the code for existing validators which should give you an idea of how to make your own. What you need to do is add a new class in that folder for your new validator, however there are a few things you should note.

  • Your validator must have its own class with a name that begins with Quform_Validator_
  • The name of the file should be the part of the class name after Quform_Validator_ and end with .php
  • Your validator class must extend Quform_Validator_Abstract
  • Your validator class must have a method called isValid() that takes the given value and returns true if the value is valid and false otherwise.
  • Inside the isValid() method you can add messages to display back to the user to tell them why the value failed validation by using the code $this->addMessage('Message to send to user');. That message will appear under the form element by default.

Naming your validator

Validators have a special naming system in order to add them to an element. If you notice two of the existing validator classes called Quform_Validator_Required and Quform_Validator_Email which are added to element using the names required and email. The conversion between short name and class name happens automatically. To convert from short name to class name, make the first letter uppercase and add Quform_Validator_ to the beginning. To convert from class name to short name make the first letter lowercase and remove Quform_Validator_ from the beginning. If you made a new validator with the class name Quform_Validator_MyNewValidator you could add it to an element using:

1
$element->addValidator('myNewValidator');
$element->addValidator('myNewValidator');

You can also add the validator to the element by passing in an instance of it:

1
$element->addValidator(new Quform_Validator_MyNewValidator());
$element->addValidator(new Quform_Validator_MyNewValidator());
Be inspired. © 2024 ThemeCatcher Ltd. 20-22 Wenlock Road, London, England, N1 7GU | Company No. 08120384 | Built with React | Privacy Policy