How do I do custom validation in Polymer Dart

139 views Asked by At

Similar to javascript and the implementation of IronValidatorBehavior how do I do custom validation in Polymer Dart?

I can create a new custom-validator which implements IronValidatorBehavior e.g.

  <dom-module id="form-input">
    <template>
      <style include='shared-styles iron-flex iron-flex-alignment'>
        :host {
          display: block;
          padding: 1em;
        }
      </style>
      <custom-validator id="validator" validator-name="jsonValidator" validator-type="json"></custom-validator>
      <paper-textarea label="[[label]]" id="body" name="body" autofocus tabindex="0"
                      validator="jsonValidator" auto-validate error-message="This is not a valid format"></paper-textarea>
    </template>
  </dom-module>

The custom-validator is written as

library main_app.custom_validator;

import 'dart:html';
import 'package:polymer/polymer.dart';
import 'package:polymer_elements/iron_validator_behavior.dart' show IronValidatorBehavior;

@PolymerRegister('custom-validator')
class  CustomValidator extends PolymerElement with IronValidatorBehavior{

  CustomValidator.created() : super.created();

  @reflectable
  bool validate(e, [_]){
    switch(validatorType) {
      case 'json':
        return textValidator(e);
    }
    return false;
  }

  bool textValidator(e){
    return false;
  }
}
1

There are 1 answers

0
fredtma On

okay, it was a typo, the above works if I change.

<custom-validator id="validator" validator-name="jsonValidator" validator-type="json"></custom-validator>

to

<custom-validator id="validator" validator-name="jsonValidator" validator-check="json"></custom-validator>

The property validatorType needs to be set to its default value of 'validator'. Instead added a new property validatorCheck, where I set the validation method name to be called.

library custom_validator;

import 'dart:mirrors' show reflect;    
import 'package:polymer/polymer.dart';
import 'package:polymer_elements/iron_validator_behavior.dart' show IronValidatorBehavior;
import 'package:validator/validator.dart' show isJSON;

@PolymerRegister('custom-validator')
class  CustomValidator extends PolymerElement with IronValidatorBehavior{
  @property
  String validatorCheck;

  CustomValidator.created() : super.created();

  @reflectable
  bool validate(value, [_]){

    if(validatorCheck.isNotEmpty) {
      Symbol sym  = new Symbol(validatorCheck);
      return reflect(this).invoke(sym, [value]).reflectee;
    }
    return false;
  }

  bool json(String value, [_]){

    if(value.isNotEmpty) {
      return isJSON(value);
    }
    return true;
  }
}