Skip to content

FR: Create a component that adds validation and error messages to any form control #7891

Open

Description

@aitboudad

Bug, feature request, or proposal:

feature request

What is the current behavior?

can't use checkbox and radio inside form-field.

What is the use-case or motivation for changing an existing behavior?

form-field provide a common way to display field description (hints) and message errors and I would like to have the same behavior for checkbox and radio.

Activity

  1. halukkaramete commented on Oct 22, 2017

    @halukkaramete
    <mat-form-field class="example-medium-width">
            <mat-select matInput name="cars" [(ngModel)]="vehicles.cars" placeholder="Cars" multiple #field_cars="ngModel">
                <mat-option *ngFor="let car of cars" [value]="car">
                    {{ car }}
                </mat-option>
            </mat-select>
    
        </mat-form-field>
    

    The Select implementation here is pretty standard for template-driven forms and it works like a charm. Thanks to the "multiple" here, one can select multiple values and then cars are submitted nicely which are all part of one single variable. Easy to cycle thru, easy to paint. No maps to deal with, No code to manage indexes, none of that. You get your cars as an array! Just cannot get any better than that.

    I hope that when the checkbox implementation is done, it would be done the same way so it will be as easy and as consolidated as the select implementation in my example. I should be able to group checkboxes under one group and handle that hassles free just like the current select box

  2. added
    feature
    P3
    on Nov 7, 2017
  3. leocaseiro commented on Nov 8, 2017

    @leocaseiro
    Contributor

    How about add mat-slider to the list?

  4. leocaseiro commented on Nov 8, 2017

    @leocaseiro
    Contributor

    Very Ugly temporary hack that hurts

    Wrap a mat-form-filed with always floatPlaceholder and add a matInput that it's display:none.

    <mat-form-field floatPlaceholder="always" class="mat-form-field--no-underline">
      <!-- the matInput with display:none makes the magic. It's ugly, I've warned you -->
      <input matInput placeholder="Input" style="display: none" >
      <mat-radio-group>
        <mat-radio-button value="1">Option 1</mat-radio-button>
        <mat-radio-button value="2">Option 2</mat-radio-button>
      </mat-radio-group>
    </mat-form-field>

    Now, we just need a workaround to remove the mat-input-underline.

    .mat-form-field--no-underline .mat-input-underline {
      background-color: transparent;
    }

    Result

    screen shot 2017-11-08 at 1 33 06 pm

    PS: Make sure you share your formControlName between mat-radio-group/mat-checkbox and the ugly [matInput] {display:none}

    Eq: http://plnkr.co/edit/NrihcY?p=preview

  5. leocaseiro commented on Nov 14, 2017

    @leocaseiro
    Contributor

    I was learning about the mat-selection-list and I've realized that it comes with a Label as [mat-subheader].

    It turned out it works for checkboxes and radio group as well.

    Try something like so:

    RadioGroup

    <mat-list>
        <h3 mat-subheader>Label for RadioGroup</h3>
        <mat-radio-group class="example-radio-group" [(ngModel)]="favoriteSeason">
        <mat-radio-button class="example-radio-button" *ngFor="let season of seasons" [value]="season">
          {{season}}
        </mat-radio-button>
      </mat-radio-group>
    </mat-list>

    Checkbox Group

    <mat-selection-list #groceries>
      <h3 mat-subheader>Groceries</h3>
    
      <mat-list-option checkboxPosition="before" value="bananas">Bananas</mat-list-option>
      <mat-list-option checkboxPosition="before" selected value="oranges">Oranges</mat-list-option>
      <mat-list-option checkboxPosition="before" value="apples">Apples</mat-list-option>
      <mat-list-option checkboxPosition="before" value="strawberries">Strawberries</mat-list-option>
    </mat-selection-list>

    Eq: https://plnkr.co/edit/k73FSy?p=preview

  6. mmalerba commented on Nov 14, 2017

    @mmalerba
    Contributor

    @tinayuangao I don't think we want to have radio buttons or checkboxes inside of form fields. form fields are only intended for things that have the floating label & underline style that input and select share. But error messages on radio & checkboxes is a reasonable request

  7. leocaseiro commented on Nov 14, 2017

    @leocaseiro
    Contributor

    Perhaps what is missing is a label that could be used as a field description for fields, such as radio-group, checkbox list, slider and some others

  8. leocaseiro commented on Nov 16, 2017

    @leocaseiro
    Contributor

    I guess we can always use Material Typography such as .mat-h4 or just wrap the <h4> in a .mat-typography:

    <section class="mat-typography">
      <h4>Label for RadioGroup</h4>
      <mat-radio-group class="example-radio-group" [(ngModel)]="favoriteSeason">
        <mat-radio-button class="example-radio-button" *ngFor="let season of seasons" [value]="season">
          {{season}}
        </mat-radio-button>
      </mat-radio-group>
    </section>
  9. oktav777 commented on Jan 29, 2018

    @oktav777

    Also mat-selection-list should be wrapable in mat-form-field too, for a common style of validation messages, hints, etc.

  10. anthony-o commented on May 15, 2018

    @anthony-o

    I've just created a new issue (#11333) presenting the expected behavior in another way: I just asked to support validation errors on such inputs.

  11. ruant commented on Jun 23, 2018

    @ruant

    Just wondering how this hasn't been implemented.
    This must be a must for a lot of people. (Pun intended)

  12. 35 remaining items

  13. salem017 commented on Nov 3, 2020

    @salem017

    Any update on it. I use the alternative methods
    <div class="col-lg-6"> <div class="full-width"> <mat-checkbox formControlName="is_active">Utilisateur active</mat-checkbox> </div> </div>
    Form control Name work on this case

  14. herman-rogers commented on Feb 24, 2021

    @herman-rogers

    Still a problem in 2021 - I think the general attitude is that "we know whats best for you" and so the workarounds continue.

    We were able to make this work (for us at least) by adding in a custom label and relevant form errors below the checkbox.

    <div class="flex-column p-b-large">
      <label for="exampleCheck">
        Checkbox example label:
        <span class="required" aria-hidden="true"></span>
      </label>
    
      <mat-checkbox id="exampleCheck" formControlName="checked">
        I Accept
      </mat-checkbox>
    
      <mat-error *ngIf="formErrors('checked')">
        You must accept to continue.
      </mat-error>
    </div>
  15. cwuerzlhuber commented on May 10, 2021

    @cwuerzlhuber

    Also having same need, to add proper error messages to checkbox or radio groups.

    @herman-rogers, your workaround is also just working partly. In that way the mat-error will not be correctly linked to the checkbox controls, so the error will not be correctly announced via screen readers for example. Normally the mat-form-field connects those and also adds all the necessary aria attributes, to make the error also accessible.

  16. jcphlux commented on Aug 16, 2021

    @jcphlux

    Here is my hacky contribution inspired by @leocaseiro. I needed validation. I did not need labels so see @leocaseiro example for that.

    // This is all for a hacky fix to make radio buttons work with validation
    .form-field-radio-group {
      &.mat-form-field-invalid .mat-radio-group{
        color: red;
        ::ng-deep .mat-radio-outer-circle{
          border-color: red;
        }
      }
      .mat-input-element {
        display: none
      }
      ::ng-deep .mat-form-field-underline {
          display: none
      }
    }
    <mat-form-field class="form-field-radio-group">
      <input matInput formControlName="stuff">
      <mat-radio-group formControlName="stuff">
        <mat-radio-button value="1">Option 1</mat-radio-button>
        <mat-radio-button value="2">Option 2</mat-radio-button>
      </mat-radio-group>
      <mat-error *ngIf="stuff.invalid">{{getErrorMessage()}}</mat-error>
    </mat-form-field>
  17. rozhanroukhosh commented on Sep 8, 2021

    @rozhanroukhosh

    2021 and still the issue is around for the checkbox!!!

  18. DanielHabenicht commented on Jan 7, 2022

    @DanielHabenicht

    I've implemented a Directive to emulate the MatFormAccessor for any NgControl, which you would use like this:

    <mat-form-field>
      <mat-label>Application Active</mat-label>
      <mat-slide-toggle formControlName="active" workaroundMatFormAccessor>
        Active
      </mat-slide-toggle>
    </mat-form-field>

    Should work for other usecases but I didn't test it yet, maybe I will setup a small npm package for it.

    Code:
    https://gist.github.com/DanielHabenicht/b98beadb1f8e099f942053076f835bcc

  19. palmtreefrb commented on Feb 4, 2022

    @palmtreefrb

    I've implemented a Directive to emulate the MatFormAccessor for any NgControl, which you would use like this:

    <mat-form-field>
      <mat-label>Application Active</mat-label>
      <mat-slide-toggle formControlName="active" workaroundMatFormAccessor>
        Active
      </mat-slide-toggle>
    </mat-form-field>
    

    Should work for other usecases but I didn't test it yet, maybe I will setup a small npm package for it.

    Code: https://gist.github.com/DanielHabenicht/b98beadb1f8e099f942053076f835bcc

    @DanielHabenicht
    Thanks, this works for me with mat-checkbox.

          <mat-form-field class="demo-full-width">
            <mat-label>Active</mat-label>
            <mat-checkbox formControlName="active" workaroundMatFormAccessor>
            </mat-checkbox>
          </mat-form-field>
    
  20. wshaver commented on Feb 7, 2022

    @wshaver

    I've implemented a Directive to emulate the MatFormAccessor for any NgControl, which you would use like this:
    Code: https://gist.github.com/DanielHabenicht/b98beadb1f8e099f942053076f835bcc

    Thanks @DanielHabenicht that saved me a bunch of time!

    If you're using an older version of Angular that doesn't implement hasValidator you can do this instead for the required() getter in WorkaroundMatFormAccessorDirective

    get required(): boolean {
        const control = this.ngControl.control;
        if (!(control && control.validator)) {
          return false;
        }
        const validator = control.validator({} as AbstractControl);
        return validator && validator.required;
      }
    
  21. frozenfrank commented on Mar 17, 2023

    @frozenfrank

    It's now 2023. Any comment on why this feature is no longer under consideration? @andrewseguin

  22. andrewseguin commented on Mar 22, 2023

    @andrewseguin
    Contributor

    There are a couple reasons that we won't be able to commit to this work. The main reason is simply that supporting this is a lower priority than the current work of moving towards the latest Material Design spec. Second, there is no spec that we could use to implement errors for components other than input and select.

    We would truly love to add this in (and many other highly requested features), but unfortunately we only have so many resources to work with.

  23. meblum commented on Feb 4, 2025

    @meblum

    If you simply want the radio button to be red when invalid, you can do something like

    .ng-submitted .mat-mdc-radio-group.ng-invalid {
      ::ng-deep .mdc-radio__outer-circle {
        border-color: var(--mdc-outlined-text-field-error-outline-color, var(--mat-sys-error)) !important;
      }
    }
  24. rbalet commented on Mar 24, 2025

    @rbalet

    If you simply want the radio button to be red when invalid, you can do something like

    .ng-submitted .mat-mdc-radio-group.ng-invalid {
    ::ng-deep .mdc-radio__outer-circle {
    border-color: var(--mdc-outlined-text-field-error-outline-color, var(--mat-sys-error)) !important;
    }
    }

    If you want to avoid the !important flag, but also don't want it to be red on a disabled field ;)

    .ng-submitted
      .mat-mdc-radio-group.ng-invalid
      .mat-mdc-radio-button
      .mdc-radio__native-control:enabled:not(:checked)
      + .mdc-radio__background
      > .mdc-radio__outer-circle {
      border-color: var(--mdc-outlined-text-field-error-outline-color, var(--mat-sys-error));
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P5area: material/form-fieldfeature

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions