Soyong
Soyong

Reputation: 188

Angular 2 required validation

I am struggling with the default required validator of angular forms. I've got a form with a single input field and one submit button.

I have two files:

Code:

In the .ts file I build a form with the formbuilder:

exampleForm: Formgroup
constructor(protected pb: Formbuilder){
  this.exampleForm = fb.group({
    name: ['', Validators.required]
  });
}

get isFormValid: boolean {
  return this.exampleForm.valid;
}

template:

<form [formGroup]="exampleForm">
  <input type="text" formControlName="name">
  <button type="submit" [disabled]="!isFormValid" id="save-button">Submit</button>
</form>

Now when the input field is empty, the button is also disabled (due to the validator). But when I enter something into the field, I cannot press directly onto the button, I have first to lose focus on the input field. How can I change that behaviour?

Upvotes: 2

Views: 5466

Answers (1)

Gili Yaniv
Gili Yaniv

Reputation: 3221

As long as the input is focused, the form validation will fail because as far as the form knows the fields are not filled.

A workaround is not to use your validation method. If the only thing you care about is for the input fields not to be empty you can do something like :

<form [formGroup]="exampleForm">
  <input type="text" formControlName="name" [(ngModel)]="someName">
  <button type="submit" [disabled]="someName==''" id="save-button">Submit</button>
</form>

Now the button will be disabled only if fields are empty. For more complex logic (For example some regex) you should build a custom validation method. For example :

  isValidEmail(): ValidatorFn {
    return (control: FormControl): string[] => {
      if (!control || !control.value || control.value == "")
        return null;
      if (this.regexService.email.test(control.value))
        return null;

      return ["Invalid email"]
    };
  }

And init the validate method in formBuilder

  initFormGroup() {
    this.authenticateForm = this.formBuilder.group(
      {
        email: ['',
          this.isValidEmail()
        ],        
      }
    );
  }

Upvotes: 3

Related Questions