Is there a way to simply validate a form field with a regular expression?

I thought about something like this:

<field name="firstname" type="text" label="Firstname"
       validate="regex" regex=".*" />

You can use Client Side Validation for this, however You will need to make a Custom Form Field for this to happen.

Assuming you're using Joomla 3.4, you first need to initialise the validation script, like so:


Then for your field, you need to add the class validate-changeme

<field name="firstname" type="text" label="Firstname" class="validate-changeme" />

Then in your custom form field script, you can add your regex for the validation like so:

$doc = JFactory::getDocument();
       document.formvalidator.setHandler('changeme', function(value) {
          return regex.test(value);

Remember to replace changeme with what ever suits your needs.

Hope this helps

  • Thx for your answer, but frontend validation is only a cosmetic thing. I found out that the JFormRule class is a simple regex validation class but doesn't find a way to use it directly.
    – Harald Leithner
    Aug 21 '15 at 13:14
  • @HaraldLeithner - Ahh yes, you're right. Have a look at this question/answer
    – Lodder
    Aug 21 '15 at 13:23
  • your link is wrong, could you fix it?
    – Harald Leithner
    Aug 21 '15 at 13:41
  • @HaraldLeithner - Oops, sorry: joomla.stackexchange.com/questions/4037/…
    – Lodder
    Aug 21 '15 at 13:50

If there is no native answer I have a solution to do this with an own JFormRule class.

Create a file in your component/models/form/rules directory called regex.php Insert the source below

class componentnameFormRuleRegex extends JFormRule {

    public function test(&$element, $value, $group = null, &$input = null, &$form = null)   {

        $this->regex = (string)$element['regex'];

        return parent::test($element, $value, $group, $input, $form);

Add the path to your rules directory to the addRulePath attribute in the xml file and add validate="componentname.regex" and regex="$regularexpression$" to the field you want to validate.

The class adds the value of the regex attribute to the JFormRule and uses the native test function for validation.

  • This looks like a winning solution. Might you award yourself the green tick to mark this page as resolved?
    – mickmackusa
    Apr 22 '19 at 5:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.