简体   繁体   English

Typescript class 属性的类验证器

[英]Typescript Class-Validator for property of class

I was trying to use the class-validator decorator library for the validation processes.我试图将类验证器装饰器用于验证过程。 So, I was implemented on my sample project.所以,我在我的示例项目中实现了。 But, it is not working.但是,它不起作用。 The sample project is trying to create sample projects with user inputs and I am trying to check those inputs(example on my code I am trying to validate contains of title with that class-validator. But, decorators are executing before the set of value of input elements. So, the title looks empty all time, and validation fails.示例项目正在尝试使用用户输入创建示例项目,并且我正在尝试检查这些输入(例如我的代码中的示例,我正在尝试使用该类验证器验证标题包含。但是,装饰器在值的集合之前执行输入元素。因此,标题一直是空的,并且验证失败。

What I am missing?我错过了什么? How can I use that library for valid to upcoming value from inputs?如何使用该库从输入中获取有效到即将到来的值?

My app.ts = >我的 app.ts = >


import { validate, Contains } from "class-validator";

class ProjectInput {
  templateElement: HTMLTemplateElement;
  hostElement: HTMLDivElement;
  formElement: HTMLFormElement;

  @Contains("hello")
  titleInputElement: HTMLInputElement;

  descriptionInputElement: HTMLInputElement;
  peopleInputElement: HTMLInputElement;

  constructor() {
    this.templateElement = <HTMLTemplateElement>(
      document.getElementById("project-input")!
    );
    this.hostElement = <HTMLDivElement>document.getElementById("app")!;
    const importedNode = document.importNode(
      this.templateElement.content,
      true
    );
    this.formElement = <HTMLFormElement>importedNode.firstElementChild;
    this.formElement.id = "user-input";

    this.titleInputElement = <HTMLInputElement>(
      this.formElement.querySelector("#title")
    );

    this.descriptionInputElement = <HTMLInputElement>(
      document.getElementById("description")
    );

    this.peopleInputElement = <HTMLInputElement>(
      document.getElementById("people")
    );
    this.configure();
    this.attach();
  }

  private submitHandler(event: Event) {
    event.preventDefault();
    console.log(this.titleInputElement.value);
  }

  private configure() {
    this.formElement.addEventListener("submit", this.submitHandler.bind(this));
  }
  private attach() {
    this.hostElement.insertAdjacentElement("afterbegin", this.formElement);
  }
}

const prjInputExample = new ProjectInput();
validate(prjInputExample).then((errors) => {
  // errors is an array of validation errors
  if (errors.length > 0) {
    console.log("validation failed. errors: ", errors);
  } else {
    console.log("validation succeed");
  }
});

index.html =>索引.html =>


<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>ProjectManager</title>
    <link rel="stylesheet" href="app.css" />
    <script src="bundles/bundle.js" defer></script>
  </head>
  <body>
    <template id="project-input">
      <form>
        <div class="form-control">
          <label for="title">Title</label>
          <input type="text" id="title" />
        </div>
        <div class="form-control">
          <label for="description">Description</label>
          <textarea id="description" rows="3"></textarea>
        </div>
        <div class="form-control">
          <label for="people">People</label>
          <input type="number" id="people" step="1" min="0" max="10" />
        </div>
        <button type="submit">ADD PROJECT</button>
      </form>
    </template>
    <template id="single-project">
      <li></li>
    </template>
    <template id="project-list">
      <section class="projects">
        <header>
          <h2></h2>
        </header>
        <ul></ul>
      </section>
    </template>
    <div id="app"></div>
  </body>
</html>

You placed validate method just inside app.ts script.您将 validate 方法放在 app.ts 脚本中。 It is invoked when the script is executed, so at the page load.它在脚本执行时调用,因此在页面加载时调用。 If I understand you well you want to make validation when user type in another character into titleInputElement.如果我理解你,你想在用户在 titleInputElement 中输入另一个字符时进行验证。 You can achieve it via您可以通过

@Contains('hello')
titleValue: string;

titleInputElement.addEventListener('input', event => {
    this.titleValue = this.titleInputElement.value;
    validate(this);
})

Worth to mention that you need to validate other property than titleInputElement: HTMLElement .值得一提的是,您需要验证titleInputElement: HTMLElement之外的其他属性。 As docs says:正如文档所说:

@Contains(seed: string) Checks if the string contains the seed. @Contains(seed: string) 检查字符串是否包含种子。

So it's gotta be string property (in my example it's titleValue)所以它必须是字符串属性(在我的例子中是titleValue)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM