代码之家  ›  专栏  ›  技术社区  ›  Alfa Bravo

在数据库中存储表单验证规则

  •  0
  • Alfa Bravo  · 技术社区  · 6 年前

    我有一个控件界面,如下所示:

    export class IFormControl {
        type: string;
        label: string;
        name: string;
        value?: string;
        disabled?: boolean;
        placeholder?: string;
        validation?: [];
        options?: [];
    } 
    

    在从数据库获取信息后,我的组件中应该是什么样子的示例:

        {
            type: 'input',
            label: 'Full name',
            name: 'name',
            placeholder: 'Enter your name',
            validation: [Validators.required, Validators.minLength(4)],
            disabled: false
        }
    

    一切正常,但我不确定存储验证规则的最佳方式是什么?

    目前,我正在考虑将整行代码转换成字符串,并将其存储在db“text”字段中。然后当我找回它时,我会得到字符串 'Validators.required, Validators.minLength(4)' ['Validators.required, Validators.minLength(4)'] ,然后用正则表达式去掉所有引号 [Validators.required, Validators.minLength(4)]

    1 回复  |  直到 6 年前
        1
  •  0
  •   Eliseo    6 年前

    这只是一个想法(我没有时间编写代码)。

    假设您有一个类似json的

    [
    {
       type: 'input',
       label: 'Full name',
       name: 'name',
       placeholder: 'Enter your name',
       validation: '1,2',
       args:'null,3'
    }
    {
       type: 'input',
       label: 'Full name',
       name: 'name2',
       placeholder: 'Enter your name2',
       validation: '1,2',
       args:'null,3'
    }
    ]
    

    您可以使用以下服务:

    getFormModel()
    {
      return httpClient.get("...").pipe(
        map(result=>{
          result.map(res=>{
             let validators=res.validation.split(,)
             let args=res.validation.split(,)
             let validator:any[]=[]
             for (let i=0;i<validators.length;i++)
             {
                   switch (validators[i])
                   {
                     case 1:
                        validator.push(Validators.required);
                        break;
                     case 2:
                        validator.push(Validators.MinLength(+args[i]);
                        break;
             }
             return 
             {
               type: res.type,
               label: res.label,
               name: res.name,
               placeholder: res.placeholder,
               validators:validator;
             }
    
          })
       })
    )
    }
    

    当您订阅时,您可以创建一个表单组并将表单组的模型存储在模型中,如

    myservice.getFormModel().subscribe(result=>
         let controls:any={}
         result.forEach(res=>{
            controls[res.name]=new FormControl('', res.validators)
         }
         this.myForm=FormGroup(controls)
         this.model=result;
    )
    

    和显示一样

    <form formGroupName="myForm">
      <div *ngFor="let control in model">
          <input [formControlName]="control.name" 
                 [placeholder]="control.placeholder"/>
      </div>
    </form>
    

    注意:一旦你有了“模型”,你就可以像这样显示控件 the response of the question (stackblitz更为复杂)