Validations / Custom validations

You can also easily define your own custom validations to be applied to current component and/or children. For example, say we wanted to validate that our comment text field in our form only contained alphanumeric characters. First, you need to a specially named method to your component, which starts with _validate_ followed by the desired custom validation name:

export class CommentFormComponent extends extend_as("CommentFormComponent").mix(Component).with() {

  ...

  _validate_isAlphanumeric(field_name,v) {
    var field_value = this.get(field_name);
    if(field_value == null || /^[a-zA-Z0-9]*$/.test(field_value))
      this.validation_errors[field_name].push(
        this._getValidationErrorMessage("should only contain letters an numbers", v)
      );
  }
}

In this case, we wanted to name our validation isAlphanumeric, so we created a method named _validate_isAlphanumeric Inside the method, this refers to the component to which the validation is applied (in our case, a FormFieldComponent representing <textara>, which is the child of the CommentFormComponent, where we're defining this validation).

Now we can just add the validation to the list of existing ones and it will work:

export class CommentFormComponent extends extend_as("CommentFormComponent").mix(Component).with() {
  constructor() {
    super();

    this.validations = {
      "content.value": { "isNotNull"    : true   },
      "content.value": { "isLongerThan" : 5      },
      "content.value": { "isAlphanumeric" : true }
    };

  }
}