Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Form Fields Display as Invalid Without User Interaction #1680

Closed
2 tasks done
pavan6014 opened this issue Feb 6, 2025 · 1 comment · Fixed by #1682
Closed
2 tasks done

Form Fields Display as Invalid Without User Interaction #1680

pavan6014 opened this issue Feb 6, 2025 · 1 comment · Fixed by #1682
Labels
triage We discuss this topic in our internal weekly

Comments

@pavan6014
Copy link

pavan6014 commented Feb 6, 2025

Prerequisites

  • I have read the Contributing Guidelines.
  • I have not leaked any internal/restricted information like screenshots, videos, code snippets, links etc.

What happened?

Requirement:
All fields are required fields Name, External target type, Namespace, Button.
"ADD" button is going to validate the form, this button is disabled until form is valid.

Here is the stackblitz example: https://stackblitz.com/edit/bvquhwlw-lcec2rb4?file=src%2Fvalidation.ts,src%2Fapp%2Fapp.module.ts

Output of above stackblitz example:
Image

Name: Input Text
External target type: Select drop down
Namespace: Input (Conditional render field if external target type is "OPC UA")
Button: button is going to validate the form, this button should be disabled until form is valid.

Description:
We have encountered an issue where all form fields are displayed as invalid by default, even if there has been no user interaction. This behavior is causing confusion for users and affecting the form's usability.

Additional Information:
We have implemented the below custom customRequiredValidator to address the issue as suggested in IX guidelines:

This approach has issues with validating form fields while submitting. The form fields should not display as invalid until the user interacts with them, and the submit button should be disabled by default as fields are required.

export function customRequiredValidator(): ValidatorFn {
  return (control: AbstractControl) => {
    if (!control.untouched) {
      return Validators.required(control);
    }
    return null;
  };
}

Expected Behavior:
Form fields should not be displayed as invalid until the user interacts with them (e.g., focuses and blurs the field). Additionally, the submit button should be disabled by default as fields are required.

Image

Example:
We have followed guidelines from IX customRequiredValidator approach, here the ADD button is enabled even though no values are entered. It should be disabled.
https://stackblitz.com/edit/bvquhwlw-nfd16esa?file=src%2Fvalidation.ts,src%2Fapp%2Fapp.module.ts

What type of frontend framework are you seeing the problem on?

Angular

Which version of iX do you use?

2.6.1

Code to produce this issue.

import { Component, Input, OnInit } from '@angular/core';
import {
  AbstractControl,
  FormBuilder,
  FormGroup,
  ValidatorFn,
  Validators,
  ValidationErrors,
} from '@angular/forms';

export function customRequiredValidator(): ValidatorFn {
  return (control: AbstractControl) => {
    if (!control.untouched) {
      return Validators.required(control);
    }
    return null;
  };
}

@Component({
  selector: 'app-example',
  template: `
    <form novalidate [formGroup]="addReferenceForm" (ngSubmit)="onSubmit($event)">
      <ix-layout-auto>
        <ix-input label="Name *" formControlName="name" placeholder="NAME"
          class="w-100" invalid-text="Enter valid name"></ix-input>

        <ix-select label="External target type*" data-colspan="2"
          formControlName="externalTargetType"
          invalid-text="Enter valid external target type">
          <ix-select-item value="OPC_UA" label="OPC UA"></ix-select-item>
          <ix-select-item value="Eclass" label="Eclass"></ix-select-item>
          <ix-select-item value="CDD" label="CDD"></ix-select-item>
          <ix-select-item value="Ontology" label="Ontology"></ix-select-item>
        </ix-select>

        <!-- Conditional render fields for OPC_UA -->
        <ix-input label="Namespace" formControlName="namespace"
          placeholder="Namespace" class="w-100" invalid-text="Enter valid namespace"
          *ngIf="addReferenceForm.get('externalTargetType')?.value === 'OPC_UA'"></ix-input>

      </ix-layout-auto>

      <ix-button class="ms-2 mt-2" variant="primary" type="submit" onkeypress 
          [disabled]="addReferenceForm.invalid">Add
      </ix-button>
    </form>
  `,
})
export default class Validation implements OnInit {
  addReferenceForm!: FormGroup;

  constructor(private readonly fb: FormBuilder) {}

  ngOnInit(): void {
    this.initForm();
  }

  initForm(): void {
    this.addReferenceForm = this.fb.group({
      name: ['', customRequiredValidator()],
      externalTargetType: ['', customRequiredValidator()],
      namespace: [''],
    });

    this.addReferenceForm
      .get('externalTargetType')
      ?.valueChanges.subscribe((value) => {
        this.updateFormFields(value);
      });
  }

  updateFormFields(externalTargetType: string): void {
    const namespaceControl = this.addReferenceForm.get('namespace');
    namespaceControl?.clearValidators();
    namespaceControl?.setValue('');

    switch (externalTargetType) {
      case 'OPC_UA':
        namespaceControl?.setValidators([customRequiredValidator()]);
        break;
    }

    namespaceControl?.updateValueAndValidity();
  }

  onSubmit(event: SubmitEvent) {
    console.log(event);
    event.preventDefault();
  }
}
@pavan6014 pavan6014 added the triage We discuss this topic in our internal weekly label Feb 6, 2025
@danielleroux
Copy link
Collaborator

@pavan6014 I will close this here because its already reported here: #1638

/close

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
triage We discuss this topic in our internal weekly
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants