6

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=".*" />
3

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:

JHtml::_('behavior.formvalidator');

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();
$doc->addScriptDeclaration("
    jQuery(document).ready(function(){
       document.formvalidator.setHandler('changeme', function(value) {
          regex=/^\d{4}-\d{2}-\d{2}$/;
          return regex.test(value);
       });
    });
");

Remember to replace changeme with what ever suits your needs.

Hope this helps

3

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 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.