Created
September 5, 2025 10:43
-
-
Save Armenvardanyan95/c01813bee367a3ed0df1269b37d19979 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function notEmptyArray( | |
path: FieldPath<unknown[]>, | |
// define a condition for when to perform a check | |
// by default, validate always | |
options: {when: () => boolean} = {when: () => true}, | |
) { | |
validate(path, (ctx) => { | |
const value = ctx.value(); | |
if (options.when() && value.length === 0) { | |
return customError({ | |
kind: 'notEmptyArray', message: 'Array must not be empty' | |
}); | |
} | |
return null; | |
}); | |
} | |
@Component({ | |
template: | |
<ul> | |
@for (item of form().value(); track item) { | |
<li>{{item}}</li> | |
} | |
</ul> | |
<label for="allowEmpty"> | |
Allow empty array | |
</label> | |
<input id="allowEmpty" type="checkbox" [checked]="allowEmpty()" (change)="allowEmpty.set(!allowEmpty())" /> | |
<form> | |
<button type="button" (click)="addItem()">Add Item</button> | |
</form> | |
@for (error of form().errors(); track error.kind) { | |
<div class="error">{{error.message}}</div> | |
}, | |
}) | |
export class App { | |
items = signal<string[]>([]); | |
allowEmpty = signal(false); | |
protected form = form( | |
this.items, | |
(items) => { | |
notEmptyArray(items, {when: () => !this.allowEmpty()}); | |
} | |
); | |
addItem() { | |
this.items.update(items => [...items, randomText()]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment