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.


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" />');
|improve this answer|||||

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.