项目作者: Gr33nbl00d

项目描述 :
Library to validate input with @Validate decorator
高级语言: TypeScript
项目地址: git://github.com/Gr33nbl00d/vue-class-decorator-validation.git
创建时间: 2019-10-07T15:47:07Z
项目社区:https://github.com/Gr33nbl00d/vue-class-decorator-validation

开源协议:MIT License

下载


vue-class-decorator-validation

Next generation decorator based Validation Framework

Use decorators to define how your editable properties should be validated.
The validation classes can also be used on server side without any dependency to vue.

STILL ALPHA!

Installation

Install packages with
npm install vue-class-decorator-validation themis-validation-rules-common —save

Integration via mixin or global mixin

Mixin definition:

  1. @Component({mixins: [AnnotationValidationMixin]})
  2. export default class MyComponentClass extends VueControllerNew {

Example:

Vue HTML CODE:

  1. <template>
  2. <v-text-field v-model="myText" :error-messages="viewValidation.getFieldErrorTexts('myText',textProcessor)"></v-text-field>
  3. <!-- Get all errormessages for the field "myText", use the textProcessor to translate string constants to localized messages -->
  4. </template>

Vue Typescript CODE:

  1. //Mixin definition
  2. @Component({mixins: [AnnotationValidationMixin]})
  3. export default class MyComponentClass {
  4. //Validation rule definition for myText property
  5. @Validate(new Validator([new MandatoryRule()]))
  6. private myText: string;
  7. private viewValidation: VueControllerValidation;
  8. constructor() {
  9. super();
  10. //For Internationalization use here your favorite I18N Framework
  11. this.textProcessor = {
  12. processText(errorTextTemplate: string, object: any): string {
  13. return errorTextTemplate;
  14. }
  15. }
  16. }
  17. save() {
  18. //programatically check if any property is invalid
  19. if (this.viewValidation.isComponentInvalid() == false) {
  20. //save data
  21. }
  22. }

JSFiddle

JSFiddle

ValidationRules

Consist of an errorTextTemplate which will be given to your I18N framework to be translated to a displayable text and a method to validate the value.

  1. export class MandatoryRule extends ValidationRule {
  2. //validation_input_required can be translated to localised text
  3. //or error codes on server side
  4. getErrorTextTemplate(): string {
  5. return "validation_input_required";
  6. }
  7. // method to check the value
  8. isValid(value): boolean {
  9. return value != undefined && value != null && value != "";
  10. }
  11. }

Validator

A validator contains multiple rules which are needed to validate an object.

On the fly validator definition
Validators can be defined on the fly inside the annotation

  1. @Validate(new Validator([new MandatoryRule(),new RegExRule("[A-Z]*","big_letter_rule")]))

Predefined Validators (can also be reused on backend side)
If values need to be checked on multiple components and also on the backend,
it makes sense to create an own class for this specific rule set.
This validator can than easily be reused on different components and also on the backend.

  1. import {Validator} from "themis-validation-core";
  2. import {MandatoryRule, MaxLengthRule, MinLengthRule} from "themis-validation-rules-common";
  3. const USERNAME_MIN_LENGTH = 4;
  4. const USERNAME_MAX_LENGTH = 16;
  5. export default class UsernameValidator extends Validator {
  6. constructor() {
  7. super();
  8. this.validationRules.push(new MandatoryRule());
  9. this.validationRules.push(new MinLengthRule(USERNAME_MIN_LENGTH));
  10. this.validationRules.push(new MaxLengthRule(USERNAME_MAX_LENGTH));
  11. }
  12. }
  13. @Component({mixins: [AnnotationValidationMixin]})
  14. export default class MyComponentClass {
  15. @Validate(new UsernameValidator())
  16. private userName: string;
  17. constructor() {
  18. super();
  19. }
  20. }

Validation Groups

Often it is needed to group validators. For example enable validation for one or more properties if a checkbox is marked.
The @Validate decorator has a second argument which contains MetaData for this validation. The metadata object can also be used to define custom meta data like i18n prefixes or anything else you need to know to display the correct information to the user.

  1. @Validate(new Validator([new MandatoryRule()]), {groupName: 'registration'})
  2. private lastName: string;
  1. private registrationCheckboxChanged(selected:boolean) {
  2. if (selected)
  3. this.viewValidation.enableGroup('registration');
  4. else
  5. this.viewValidation.disableGroup('registration');
  6. }

Inspect/Read Validation Errors

  1. //returns true if any property which is in an enabled group contains invalid data
  2. isComponentInvalid(): boolean;
  3. //returns a list or errrors containing metadata and rules that failed
  4. getComponentErrors(): Array<ValidatorError>;
  5. //returns a list or errrors containing metadata and rules that failed
  6. //mandatory rules will be filtered out
  7. getComponentErrosWithoutMandatoryRules(): Array<ValidatorError>
  8. //returns all errors for a specific field/property
  9. getFieldErrors(fieldName): Array<ValidatorError>;
  10. //returns a list of errortexts (convenience method)
  11. getFieldErrorTexts(fieldName: string, textProcessor: TextTemplateProcessor): Array<String>;
  12. //returns true if any rule does not match
  13. isFieldInvalid(fieldName): boolean;
  14. //Possibility to check specific values for a specific field
  15. isFieldInvalidWithValue(fieldName, value): boolean;
  16. //disable a specific group of validators
  17. disableGroup(groupName: string);
  18. //enable a specific group of validators
  19. enableGroup(groupName: string);
  20. //enables all groups
  21. clearDisabledGroups();