2

What’s the best way to validate a user registration form to make sure that at least one of two fields is not empty?

I’ve tried a very simple controller but can’t get this to work past the point of trying to save the user. Any pointers with this method or for a different method entirely?

public function actionIndex() {

    $this->requirePostRequest();

    $fields = craft()->request->getPost('fields');

    $customField1 = $fields['customField1'];
    $customField2 = $fields['customField2'];

    $user = new UserModel();
    $user->email = craft()->request->getPost('email');
    $user->password = craft()->request->getPost('password');
    $user->setContentFromPost('fields');

    if ($customField1 != '' || $customField2 != '') {

        // RETURN CUSTOM ERROR

    }

    // OTHERWISE SUBMIT USER REGISTRATION REQUEST 
    // AND RETURN ANY ERRORS

    craft()->users->saveUser($user);
    $this->redirectToPostedUrl();

}
  • 1
    What if you changed the && (and) to an || (or). So your statement would now be if customField is not empty OR customField2 is not empty`... – Damon Feb 19 '16 at 11:45
  • @Damon good spot but it was a typo with the example, sorry. Edited the question. The validation part works it seems to be the saveUser part here that’s not checking out. – James Feb 19 '16 at 11:52
  • James, please re-read Damon's suggestion, I think it should in fact solve your problem. And @Damon, I think you should add it as a proper answer?! – carlcs Feb 19 '16 at 12:49
  • @carlcs the conditional is not the problem here. I didn’t set the example properly. – James Feb 19 '16 at 13:01
2

Looks like I needed to set $user->username = craft()->request->getPost('email'); for my attempt to work.

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.