From ec37d4a7825599d8e51aec706e26e9c321abce45 Mon Sep 17 00:00:00 2001 From: Yonatan Kra Date: Wed, 1 Jan 2025 13:26:24 +0200 Subject: [PATCH] fix(radio): radio singular required validation --- libs/components/src/lib/radio/radio.spec.ts | 30 +++++++++++++++++++++ libs/components/src/lib/radio/radio.ts | 11 +++++++- 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/libs/components/src/lib/radio/radio.spec.ts b/libs/components/src/lib/radio/radio.spec.ts index ed5f8c99af..6b15b4e9e0 100644 --- a/libs/components/src/lib/radio/radio.spec.ts +++ b/libs/components/src/lib/radio/radio.spec.ts @@ -143,6 +143,36 @@ describe('vwc-radio', () => { }); }); + describe('required', () => { + it('should reflect required attribute', async () => { + element.required = true; + await elementUpdated(element); + expect(element.hasAttribute('required')).toBe(true); + }); + + it('should invalidate the element when required and not selected', async () => { + element.required = true; + await elementUpdated(element); + element.checkValidity(); + expect(element.validity.valueMissing).toBe(true); + }); + + it('should set the name attribute on the proxy element so that elementals validation works', async () => { + element.name = 'test'; + await elementUpdated(element); + expect(element.proxy.name).toBe('test'); + }); + + it('should remove the proxy name attribute if removed from the element', async () => { + element.name = 'test'; + await elementUpdated(element); + + element.removeAttribute('name'); + await elementUpdated(element); + + expect(element.proxy.getAttribute('name')).toBeNull(); + }); + }); describe('change', () => { it('should be fired when a user toggles the radio', async () => { const spy = jest.fn(); diff --git a/libs/components/src/lib/radio/radio.ts b/libs/components/src/lib/radio/radio.ts index 48698f847e..bd06adaaea 100644 --- a/libs/components/src/lib/radio/radio.ts +++ b/libs/components/src/lib/radio/radio.ts @@ -86,7 +86,7 @@ export class Radio extends FormAssociatedRadio { /** * The name of the radio. See {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#htmlattrdefname | name attribute} for more info. */ - @observable + @attr override name!: string; /** @@ -121,8 +121,17 @@ export class Radio extends FormAssociatedRadio { constructor() { super(); this.proxy.setAttribute('type', 'radio'); + this.proxy.setAttribute('name', this.name); } + + /** + * @internal + */ + override nameChanged(previous: string, next: string): void { + super.nameChanged ? super.nameChanged(previous, next) : null; + next !== null ? this.proxy.setAttribute('name', this.name) : this.proxy.removeAttribute('name'); + } /** * @internal */