如何验证FormArray中的FormGroups

时间:2019-11-26 05:42:04

标签: angular

如何验证FormArray中的每个FormGroup?这里有自定义验证器:

export class GridProcessorValidator {

  static validateGroupItem(definition: ObjectDefinition) {
      return function(control: AbstractControl): ValidatorFn {
          return null;
      };
  }

}

这是表格:

this.gridProcessorForm = this.fb.group({
    propertiesSide: new FormControl(),
    objectNamesSide: new FormControl(),
    groupItems: this.fb.array([], validateGroupItem(this.myCollection))   // array of form groups that needs custom validation
});

如何在自定义验证器definitionPropertiesMatched中访问FormGroups的值,以便对其进行检查然后将其打印到无效的各个FormGroup的模板中?

模板:

*ngFor="let item of gridProcessorForm.get('groupItems').controls; let i=index"
                    [formGroupName]="i"> ...

然后我有表单字段访问器:

{{item.get('propertyName').value}}

有没有办法让我在迭代器中的某项(FormGroup)出错?

2 个答案:

答案 0 :(得分:1)

如果你写

Widget build(BuildContext context){
  return Scaffold(
    body: Center(
     child: FlatButton(
        child: Text(Login with Twitter),
         onPressed: () async{
           bool res= await signInWithGoogleAccount();
             if(!res)
              { setState(() {
                 isLoading=false;
                });
                Fluttertoast.showToast(msg: "Login failed");
              }else{  
              setState(() {
                isLoading=false;
              });
             Fluttertoast.showToast(msg: "Logged in successfully");
                            Navigator.of(context).pushReplacementNamed('/homepage');  
            }
         },
      )
    )
  );
}

您要验证整个formArray,然后您的验证函数就像

E/Twitter ( 7270): Invalid json: <?xml version="1.0" encoding="UTF-8"?><errors><error code="415">Callback URL not approved for this client application. Approved callback URLs can be adjusted in your application settings</error></errors>
E/Twitter ( 7270): com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
E/Twitter ( 7270):      at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:226)
E/Twitter ( 7270):      at com.twitter.sdk.android.core.models.SafeListAdapter$1.read(SafeListAdapter.java:45)
E/Twitter ( 7270):      at com.twitter.sdk.android.core.models.SafeMapAdapter$1.read(SafeMapAdapter.java:45)
E/Twitter ( 7270):      at com.google.gson.Gson.fromJson(Gson.java:927)
E/Twitter ( 7270):      at com.google.gson.Gson.fromJson(Gson.java:892)
E/Twitter ( 7270):      at com.google.gson.Gson.fromJson(Gson.java:841)
E/Twitter ( 7270):      at com.google.gson.Gson.fromJson(Gson.java:813)
E/Twitter ( 7270):      at com.twitter.sdk.android.core.TwitterApiException.parseApiError(TwitterApiException.java:110)
E/Twitter ( 7270):      at com.twitter.sdk.android.core.TwitterApiException.readApiError(TwitterApiException.java:95)
E/Twitter ( 7270):      at com.twitter.sdk.android.core.TwitterApiException.<init>(TwitterApiException.java:43)
E/Twitter ( 7270):      at com.twitter.sdk.android.core.Callback.onResponse(Callback.java:42)
E/Twitter ( 7270):      at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
E/Twitter ( 7270):      at android.os.Handler.handleCallback(Handler.java:794)
E/Twitter ( 7270):      at android.os.Handler.dispatchMessage(Handler.java:99)
E/Twitter ( 7270):      at android.os.Looper.loop(Looper.java:176)
E/Twitter ( 7270):      at android.app.ActivityThread.main(ActivityThread.java:6635)
E/Twitter ( 7270):      at java.lang.reflect.Method.invoke(Native Method)
E/Twitter ( 7270):      at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
E/Twitter ( 7270):      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
E/Twitter ( 7270): Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
E/Twitter ( 7270):      at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:385)
E/Twitter ( 7270):      at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:215)
E/Twitter ( 7270):      ... 18 more
E/Twitter ( 7270): Failed to get request token
E/Twitter ( 7270): com.twitter.sdk.android.core.TwitterApiException: HTTP request failed, Status: 403
E/Twitter ( 7270):      at com.twitter.sdk.android.core.Callback.onResponse(Callback.java:42)
E/Twitter ( 7270):      at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
E/Twitter ( 7270):      at android.os.Handler.handleCallback(Handler.java:794)
E/Twitter ( 7270):      at android.os.Handler.dispatchMessage(Handler.java:99)
E/Twitter ( 7270):      at android.os.Looper.loop(Looper.java:176)
E/Twitter ( 7270):      at android.app.ActivityThread.main(ActivityThread.java:6635)
E/Twitter ( 7270):      at java.lang.reflect.Method.invoke(Native Method)
E/Twitter ( 7270):      at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
E/Twitter ( 7270):      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
I/zygote64( 7270): Do partial code cache collection, code=121KB, data=74KB
I/zygote64( 7270): After code cache collection, code=121KB, data=74KB
I/zygote64( 7270): Increasing code cache capacity to 512KB
E/Twitter ( 7270): Authorization completed with an error
E/Twitter ( 7270): com.twitter.sdk.android.core.TwitterAuthException: Failed to get request token
E/Twitter ( 7270):      at com.twitter.sdk.android.core.identity.OAuthController$1.failure(OAuthController.java:94)
E/Twitter ( 7270):      at com.twitter.sdk.android.core.internal.oauth.OAuth1aService$1.failure(OAuth1aService.java:191)
E/Twitter ( 7270):      at com.twitter.sdk.android.core.Callback.onResponse(Callback.java:42)
E/Twitter ( 7270):      at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
E/Twitter ( 7270):      at android.os.Handler.handleCallback(Handler.java:794)
E/Twitter ( 7270):      at android.os.Handler.dispatchMessage(Handler.java:99)
E/Twitter ( 7270):      at android.os.Looper.loop(Looper.java:176)
E/Twitter ( 7270):      at android.app.ActivityThread.main(ActivityThread.java:6635)
E/Twitter ( 7270):      at java.lang.reflect.Method.invoke(Native Method)
E/Twitter ( 7270):      at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
E/Twitter ( 7270):      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
I/Toast   ( 7270): Show toast from OpPackageName:com.company_name.project, PackageName:com.company_name.project
E/SpannableStringBuilder( 7270): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
E/SpannableStringBuilder( 7270): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
W/ContentCatcher( 7270): Failed to notify a WebView
W/ResourceType( 7270): No package identifier when getting name for resource number 0x00000000

如果要在数组的每个组上使用验证器,则在向数组中推送formGroup时需要添加验证器,例如

this.fb.array([], validateGroupItem(this.myCollection))

您使用

static validateGroupItem(definition: ObjectDefinition) {
      return function(control: FormArray): ValidatorFn {
          return null;
      };
  }

createGroup()
{
    return this.fb.group({
      name:''
      surname:''
    },validateGroupItem(this.myCollection))
}

答案 1 :(得分:0)

您的html内部通过循环模板输入变量(在您的情况下为“ item”)访问每个表单组状态:

   *ngFor="let item of gridProcessorForm.get('groupItems').controls; let i=index"
                    [formGroupName]="i"> 
      ...

   <div *ngIf="item.invalid" class="text-danger"> Invalid !</div> 
      ...