<p>In a plugin, you can use the <a href="http://buildwithcraft.com/docs/plugins/events-reference#users-onBeforeSaveUser" rel="nofollow">onBeforeSaveUser</a> event. </p>

<p>In your plugin's main file, use the following init function:</p>

<pre><code>public function init(){
    //Tap into the onBeforeSaveUser event
    craft()-&gt;on('users.onBeforeSaveUser', function(Event $event) {

        //Get the user object from the raised event
        $user = $event-&gt;params['user'];

        //If the first name is blank, do not allow the save to continue
        if($user-&gt;firstName == '')
        {
            $event-&gt;performAction = false;
        }
    });
}
</code></pre>

CC BY-SA 3.0
2015-10-14T14:15:46.403Z
Thanks, @Aaron. That was my first port of call, however it doesn’t allow for validation (in a single request).
Joshua Baker
CC BY-SA 3.0
2015-10-14T14:07:29.303Z
2015-10-14T14:07:29.303Z
Aaron Berkowitz
<p>I just ran into this issue myself. I have custom fields assigned to the user model in the dashboard that weren't being validated. </p>

<p>Marking those fields are required in the dashboard for the user model was all I had to do to ensure that they are required using the standard Craft saveUser controller. Depending on what your validation needs are this might work for you too.</p>

CC BY-SA 3.0
2015-11-02T18:25:22.080Z
2015-11-02T18:25:22.080Z
John O
<p>At the time of writing the <code>users.onBeforeSave</code> event runs after validation, which means that we can’t add errors to the user easily.</p>

<p>The solution I’ve currently come up with is a plugin that adds custom validation rules to a user model, as well as a controller to handle the form submission.</p>

<h1>Model</h1>

<p>Firstly, I’ve extended the <code>UserModel</code> and added custom validation rules as needed.</p>

<pre class="lang-php prettyprint-override"><code>&lt;?php

namespace Craft;

class MyPlugin_UserModel extends UserModel
{
    protected function defineAttributes()
    {
        // Get the rules defined in UserModel
        $rules = parent::defineAttributes();

        // Add custom rules
        $rules['firstName'] = array(AttributeType::String, 'required' =&gt; true);
        $rules['lastName'] = array(AttributeType::String, 'required' =&gt; true);

        // If it’s a new user, require the password
        $isNewUser = !isset($this-&gt;id);
        if ($isNewUser) {
            $rules['password'] = array(AttributeType::String, 'required' =&gt; true);
        }

        return $rules;
    }
}
</code></pre>

<h1>Controller</h1>

<p>Secondly, I’ve created a controller action that will handle form submissions. This populates our custom user model with the input and runs the standard <code>validate()</code> flow.</p>

<pre class="lang-php prettyprint-override"><code>&lt;?php

namespace Craft;

class MyPlugin_UsersController extends BaseController
{
    protected $allowAnonymous = array('actionSaveUser');

    public function actionSaveUser()
    {
        $this-&gt;requirePostRequest();

        // Get input
        $post = craft()-&gt;request-&gt;getPost();

        // Create an instance of our model
        $user = new MyPlugin_UserModel($post);

        if (!$user-&gt;validate()) {
            // Add any errors from the validation to the user
            $user-&gt;addErrors($user-&gt;getContent()-&gt;getErrors());

            // Respond with errors
            if (craft()-&gt;request-&gt;isAjaxRequest()) {
                $this-&gt;returnJson(array(
                    'errors' =&gt; $user-&gt;getErrors(),
                ));
            } else {
                craft()-&gt;userSession-&gt;setError(Craft::t('Couldn’t save user.'));

                // Send the account back to the template
                craft()-&gt;urlManager-&gt;setRouteVariables(array(
                    'account' =&gt; $user
                ));
            }
        } else {
            // If all is well, run the default UsersController method
            craft()-&gt;runController('users/saveUser');
        }
    }
}
</code></pre>

<h1>Template</h1>

<p>For reference, here’s the action input in the template. Essentially, it’s just prepending the plugin handle before the default action.</p>

<pre class="lang-html prettyprint-override"><code>&lt;input type="hidden" name="action" value="myPlugin/users/saveUser"&gt;
</code></pre>

CC BY-SA 3.0
2015-10-14T15:05:15.440Z
2015-10-14T15:05:15.440Z
Joshua Baker
<p>For example, how might we ensure that <code>firstName</code> is set.</p>

<users>
How can I add custom validation rules to a new User registration?
# How can I add custom validation rules to a new User registration?

(Asked by: username_0 on 2015-10-14)

For example, how might we ensure that `firstName` is set.

**Tags:** users

---

## 3 answers

### Answer by username_0 on 2015-10-14. Score: 4 | Accepted answer

At the time of writing the users.onBeforeSave event runs after validation, which means that we can’t add errors to the user easily.
The solution I’ve currently come up with is a plugin that adds custom validation rules to a user model, as well as a controller to handle the form submission.
Model
Firstly, I’ve extended the UserModel and added custom validation rules as needed.
 true);
        $rules['lastName'] = array(AttributeType::String, 'required' => true);

        // If it’s a new user, require the password
        $isNewUser = !isset($this->id);
        if ($isNewUser) {
            $rules['password'] = array(AttributeType::String, 'required' => true);
        }

        return $rules;
    }
}

Controller
Secondly, I’ve created a controller action that will handle form submissions. This populates our custom user model with the input and runs the standard validate() flow.
requirePostRequest();

        // Get input
        $post = craft()->request->getPost();

        // Create an instance of our model
        $user = new MyPlugin_UserModel($post);

        if (!$user->validate()) {
            // Add any errors from the validation to the user
            $user->addErrors($user->getContent()->getErrors());

            // Respond with errors
            if (craft()->request->isAjaxRequest()) {
                $this->returnJson(array(
                    'errors' => $user->getErrors(),
                ));
            } else {
                craft()->userSession->setError(Craft::t('Couldn’t save user.'));

                // Send the account back to the template
                craft()->urlManager->setRouteVariables(array(
                    'account' => $user
                ));
            }
        } else {
            // If all is well, run the default UsersController method
            craft()->runController('users/saveUser');
        }
    }
}

Template
For reference, here’s the action input in the template. Essentially, it’s just prepending the plugin handle before the default action.


---

### Answer by username_1 on 2015-10-14. Score: 3

In a plugin, you can use the onBeforeSaveUser event. 
In your plugin's main file, use the following init function:
public function init(){
    //Tap into the onBeforeSaveUser event
    craft()->on('users.onBeforeSaveUser', function(Event $event) {

        //Get the user object from the raised event
        $user = $event->params['user'];

        //If the first name is blank, do not allow the save to continue
        if($user->firstName == '')
        {
            $event->performAction = false;
        }
    });
}

> **Comments:**
> **username_0**: Thanks, @Aaron. That was my first port of call, however it doesn’t allow for validation (in a single request).  

---

### Answer by username_2 on 2015-11-02. Score: 2

I just ran into this issue myself. I have custom fields assigned to the user model in the dashboard that weren't being validated.

Marking those fields are required in the dashboard for the user model was all I had to do to ensure that they are required using the standard Craft saveUser controller. Depending on what your validation needs are this might work for you too.


---

