如何以编程方式验证反应形式控件?

时间:2018-10-18 13:42:30

标签: angular angular-reactive-forms

我有一个我的反应形式的'use strict'; const Joi = require('joi'); let schema = Joi.object().keys({ personal_info: Joi.object().keys({ first_name: Joi.string().min(2).max(10).required(), last_name: Joi.string().min(2).max(10).required() }).required(), permission_level: Joi.number().min(1).max(9).required() }); const req = { personal_info: { first_name: 'AAAA', last_name: 'CCCCCC' }, permission_level: 2 }; Joi.validate(req, schema, (err) => { console.log(err); }); 对象。现在,我想以编程方式触发表单验证。

我已经使用此代码检查表单,但是未设置控件的CSS状态类,就像单击控件并在控件外部单击时所做的一样。

FtpWebRequest reqFTP = null;
        Stream ftpStream = null;

        string[] subDirs = directory.Split('/');

        string currentDir = publishUrl;

        foreach (string subDir in subDirs)
        {
            try
            {
                currentDir = currentDir + "/" + subDir;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(currentDir);
                reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                reqFTP.UseBinary = true;
                //reqFTP.UsePassive = true;
                //reqFTP.KeepAlive = true;
                reqFTP.Credentials = new NetworkCredential(userName, userPWD);
                FtpWebResponse response =  (FtpWebResponse)await reqFTP.GetResponseAsync();
                ftpStream = response.GetResponseStream();
                ftpStream.Close();
                response.Close();
            }
            catch (Exception exception)
            {

                Console.WriteLine(exception.Message);
                //directory already exist I know that is weak but there is no way to check if a folder exist on ftp...
            }
        }

3 个答案:

答案 0 :(得分:2)

您可以使用以下方式以编程方式触发验证器。

@WebMVCTest
@Import(YourComponent.class)
public MyTestClass {
}

答案 1 :(得分:0)

创建反应式表单时,您隐式地说该表单应根据特定策略更新其值和有效性。

有3种策略:

  • 模糊时
  • 更改时
  • 提交时

您可以在创建表单控件或表单组时更改更新策略。在您的情况下,更改策略应该有效。

Here is a stackblitz包含两种策略,请参阅最适合您的策略。

first = new FormControl('', {
  validators: [Validators.minLength(3)],
  updateOn: 'blur'
})
second = new FormControl('', {
  validators: [Validators.minLength(3)],
  updateOn: 'change'
})

答案 2 :(得分:0)

验证所有表单域

validateAllFormFields(formGroup: FormGroup) {
  Object.keys(formGroup.controls).forEach(field => {
    const control = formGroup.get(field);

    if (control instanceof FormControl) {
      control.markAsTouched({ onlySelf: true });
    } 
    else if (control instanceof FormGroup) {
      this.validateAllFormFields(control);
    }
  });
}