Skip to content

Instantly share code, notes, and snippets.

@Armenvardanyan95
Created September 5, 2025 10:43
Show Gist options
  • Save Armenvardanyan95/c01813bee367a3ed0df1269b37d19979 to your computer and use it in GitHub Desktop.
Save Armenvardanyan95/c01813bee367a3ed0df1269b37d19979 to your computer and use it in GitHub Desktop.
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