Sign up form

To handle form data use classes that inherit the areto/base/Model class.

model/SignUpForm.js

const Base = require('areto/base/Model');
const User = require('./User');

module.exports = class SignUpForm extends Base {
    // place methods here
};
module.exports.init(module);

Model validation

The RULES array keep the rules of model validation. Each array element is a separate rule. It applies to the listed attributes of model. The rule also is an array consisting of several elements.

  • The first element is the name of attribute with assigned rule. It may be a string or an array of strings in the case of multiple attributes.
  • The second element is the type of validator. It can be built-in validator of the Areto Framework, name of the method of the current class or a separate class. The list of built-in validator: boolean, compare, date, email, exist, file, filter, image, number, range, regexp, required, string, unique, url.
  • The third element is an object containing additional parameters for the rule. It is optional.

Rules are applied in the order of elements in array. By default, when an attribute has no value or contains errors of previous rule, it passed validation. This behavior can be changed by rule parameters: skipOnError, skipOnAnyError, skipOnEmpty. For example, when a new user registers his name and email will be checked for uniqueness only if there are no errors in previous rules.

model/SignUpForm.js

static getConstants () {
  return {
    RULES: [
      [['name', 'email', 'password', 'passwordRepeat', 'captchaCode'], 'required'],
      ['name', 'string', {min: 3, max: 24}],
      ['name', 'regexp', {pattern: /^[а-яa-z\s-]+$/i}],
      ['email', 'email'],
      ['captchaCode', require('areto/captcha/CaptchaValidator'), {
         CaptchaController: require('../controller/AuthController')
      }],
      ['password', 'string', {min: 6, max: 24}],
      ['passwordRepeat', 'compare', {compareAttr: 'password'}],
      [['name', 'email'], 'unique', {
         skipOnAnyError: true,
         targetClass: User,
         ignoreCase: true
      }]
    ],
    ATTR_LABELS: {
      captchaCode: 'Verification code'
    }
  };
}

New user registration

The signUp method checks data received from form. If there are no errors, it creates a new User model, initiates form values and pushes into database. The current session is bound to a new user after successful model saving.

User registration form

All methods working with database are asynchronous functions. They must explicitly apply a callback at the end or transfer it to another asynchronous function.

model/SignUpForm.js

async register () {
  if (await this.validate()) {
    const model = this.spawn(User);
    model.setAttrs(this);
    if (await model.save()) {
      await this.user.login(model, 0);
    } else {
      this.addError('name', model.getFirstError());
    }
  }
}