package com.alexfu.formvalidator;

import android.widget.TextView;

import com.alexfu.formvalidator.rules.ValidationRule;

import java.util.List;

/**
 * Default validator
 */

public class Validator extends AbsValidator<Void> implements ValidationAsyncTask.Callback {
  private final Callback callback;

  public Validator(Callback callback) {
    this.callback = callback;
  }

  @Override public void addRule(TextView view, List<ValidationRule> rules) {
    super.addRule(view, rules);
  }

  @Override public void addRule(TextView view, ValidationRule... rules) {
    super.addRule(view, rules);
  }

  @Override public Void performValidate(ValidationTask[] tasks) {
    new ValidationAsyncTask(ValidationAsyncTask.Mode.FORM, this).execute(tasks);
    return null;
  }

  @Override public Void performValidate(ValidationTask task) {
    new ValidationAsyncTask(ValidationAsyncTask.Mode.INPUT, this).execute(task);
    return null;
  }

  @Override
  public void onTaskCompleted(ValidationAsyncTask.Mode mode, List<ValidationResult> results) {
    int invalidHitCount = 0;

    for (int i = 0; i < results.size(); i++) {
      ValidationResult result = results.get(i);
      if (result.isValid()) {
        callback.onFieldValidationSuccessful(result.view);
      } else {
        invalidHitCount++;
        callback.onFieldValidationFailed(result.view, result.errors);
      }
    }

    if (mode == ValidationAsyncTask.Mode.FORM) {
      if (invalidHitCount == 0) {
        callback.onFormValidationSuccessful();
      } else {
        callback.onFormValidationFailed();
      }
    }
  }

  public interface Callback {
    void onFieldValidationSuccessful(TextView view);
    void onFieldValidationFailed(TextView view, List<String> errors);
    void onFormValidationSuccessful();
    void onFormValidationFailed();
  }
}

@@ -28,16 +28,79 @@
 dator;%0A%0A
+import android.text.Editable;%0Aimport android.text.TextWatcher;%0A
 import a
@@ -123,16 +123,16 @@
 xtView;%0A
-
 %0Aimport 
@@ -537,32 +537,63 @@
 e(view, rules);%0A
+    watchForTextChanges(view);%0A
   %7D%0A%0A  @Override
@@ -687,16 +687,47 @@
 rules);%0A
+    watchForTextChanges(view);%0A
   %7D%0A%0A  @
@@ -1698,24 +1698,24 @@
 ();%0A      %7D%0A
-
     %7D%0A  %7D%0A%0A 
@@ -1713,16 +1713,531 @@
  %7D%0A  %7D%0A%0A
+  private void watchForTextChanges(final TextView view) %7B%0A    TextWatcher watcher = new TextWatcher() %7B%0A      @Override%0A      public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) %7B%0A        // Ignore%0A      %7D%0A%0A      @Override%0A      public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) %7B%0A        // Ignore%0A      %7D%0A%0A      @Override public void afterTextChanged(Editable editable) %7B%0A        validate(view);%0A      %7D%0A    %7D;%0A%0A    view.addTextChangedListener(watcher);%0A  %7D%0A%0A
   public

Handle on-the-fly validation