How to use form rules programatically to validate data outside a form

by Dom   Last Updated February 10, 2019 13:10 PM - source

I've created a component where an admin can bulk upload users and I want to validate the email addresses before creating those users.

The XML definition of the form for creating or modifying a user (administrator/components/com_users/models/forms/user.xml), has the attribute validate=email on the email field. This means that Joomla will use its Joomla\CMS\Form\Rule\EmailRule class to validate any input from the email form field.

I'd like to leverage the Joomla\CMS\Form\Rule\EmailRule class for validating the email addresses which are uploaded.



Answers 1


Its possible to use the Joomla\CMS\Form\Rule\EmailRule directly within code. Just instantiate it and then call its test method. The test method requires two arguments, a SimpleXMLElement defining the field tag the value to be tested. To validate a bunch of uploaded email addresses, you would use the code

$emails; //an array of email addresses
$email_validator = new \Joomla\CMS\Form\Rule\EmailRule();
$field_element = simplexml_load_string('<field name="email" type="email" validate="email" />');
foreach( $emails as $email ) {
    if( !$email_validator->test($field_element, $email) ) {
        //deal with failed email validation
    }
}

Reviewing the Joomla\CMS\Form\Rule\EmailRule class, the SimpleXMLElement only looks for the attributes 'required', 'multiple', 'tld' and 'unique', so if you don't require these, you can actually just use simplexml_load_string('<field/>);

Using the field element definition, you can easily modify the rule's behaviour. For example, if you want to use the Joomla\CMS\Form\Rules\PasswordRule to validate passwords, then you can adjust the SimpleXMLElement string to require a minimum total length or number of symbols. The code would look like:

$field_element = simplexml_load_string('<field minimum_length="15" minimum_symbols="3" />');
Dom
Dom
February 10, 2019 12:31 PM

Related Questions


Joomla 2.5 email validation issue

Updated July 26, 2017 19:10 PM

form validation

Updated April 10, 2016 08:04 AM

BreezingForms unique user email validation problem

Updated October 17, 2017 10:10 AM

Joomla registration form validation

Updated April 08, 2017 16:10 PM

Editor stripping Script

Updated April 22, 2016 08:04 AM