Validate input and filter rows
Use this page to restrict what users may type into cells, check values against those rules before you store them, and filter a table's rows the way Excel's AutoFilter does. Filters and validation lists every option; the calls are under Data validation and AutoFilter in the WASM API, and in the Python API.
Offer a drop-down list
A List rule takes its items from formula1: a range reference such as $E$1:$E$3, or a quoted, comma-separated list such as "Low,Mid,High". addValidation returns the rule's id. Excel shows the in-cell drop-down for a list rule unless showInCellDropdown is false.
import createFormulon, { ValidationType } from '@libraz/formulon'
const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
const ws = wb.sheet(0)
ws.setValues('E1', [['Red'], ['Green'], ['Blue']])
const colours = ws.addValidation({ ranges: 'A2:A100', type: ValidationType.List, formula1: '$E$1:$E$3' })
ws.addValidation({ ranges: 'B2:B100', type: ValidationType.List, formula1: '"Low,Mid,High"' })
console.log(ws.getValidation(colours).formula1) // =$E$1:$E$3
console.log(ws.validateValue('A2', 'Green').valid) // true
console.log(ws.validateValue('A2', 'Pink').valid) // false
console.log(ws.validateValue('B2', 'Mid').valid) // true
} finally {
wb.dispose()
}from formulon import DataValidationInput, ValidationType, Workbook
with Workbook.create_default() as wb:
ws = wb[0]
ws.set_values("E1", [["Red"], ["Green"], ["Blue"]])
colours = ws.add_validation(DataValidationInput(ranges="A2:A100", type=ValidationType.LIST, formula1="$E$1:$E$3"))
ws.add_validation(DataValidationInput(ranges="B2:B100", type=ValidationType.LIST, formula1='"Low,Mid,High"'))
print(ws.get_validation(colours).formula1) # =$E$1:$E$3
print(ws.validate_value("A2", "Green").valid) # True
print(ws.validate_value("A2", "Pink").valid) # False
print(ws.validate_value("B2", "Mid").valid) # TrueAn item of an inline list matches the displayed text exactly, case included, so mid fails against "Low,Mid,High".
Allow whole numbers in a range
Whole, Decimal, Date, Time and TextLength rules compare the value with operator (a ComparisonOperator) and one or two bounds. Between and NotBetween take both formula1 and formula2. errorTitle and errorMessage are the alert Excel shows on a bad entry, and errorStyle chooses whether the alert stops the entry or only warns.
import createFormulon, { ComparisonOperator, ValidationType } from '@libraz/formulon'
const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
const ws = wb.sheet(0)
ws.addValidation({
ranges: 'B2:B100',
type: ValidationType.Whole,
operator: ComparisonOperator.Between,
formula1: '1',
formula2: '100',
errorTitle: 'Quantity',
errorMessage: 'Enter a whole number from 1 to 100.',
})
console.log(ws.validateValue('B2', 50).valid) // true
console.log(ws.validateValue('B2', 2.5).valid) // false
console.log(ws.validateValue('B2', 500).valid) // false
console.log(ws.validateValue('B2', 'ten').valid) // false
} finally {
wb.dispose()
}from formulon import ComparisonOperator, DataValidationInput, ValidationType, Workbook
with Workbook.create_default() as wb:
ws = wb[0]
ws.add_validation(DataValidationInput(
ranges="B2:B100",
type=ValidationType.WHOLE,
operator=ComparisonOperator.BETWEEN,
formula1="1",
formula2="100",
error_title="Quantity",
error_message="Enter a whole number from 1 to 100.",
))
print(ws.validate_value("B2", 50).valid) # True
print(ws.validate_value("B2", 2.5).valid) # False
print(ws.validate_value("B2", 500).valid) # False
print(ws.validate_value("B2", "ten").valid) # FalseCheck a value against a formula
A Custom rule passes when its formula is true. The formula is written for the top-left cell of the range and its relative references shift for the other cells, so C2<=B2*10 over C2:C100 compares each row's C with the same row's B.
A custom rule with a relative reference
C2:C4 carries the rule C2<=B2*10, written for C2. C3 is checked as C3<=B3*10, so each row compares its own C with its own B. 30 and 150 pass; 120 exceeds 8 × 10 = 80 and would be refused.
Powered by the real Formulon engine (WASM) — it runs entirely in your browser, nothing is uploaded.
import createFormulon, { ValidationType } from '@libraz/formulon'
const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
const ws = wb.sheet(0)
ws.setValues('B2', [[3], [8]])
ws.addValidation({ ranges: 'C2:C100', type: ValidationType.Custom, formula1: 'C2<=B2*10' })
console.log(ws.validateValue('C2', 30).valid) // true
console.log(ws.validateValue('C2', 31).valid) // false
console.log(ws.validateValue('C3', 31).valid) // true
} finally {
wb.dispose()
}from formulon import DataValidationInput, ValidationType, Workbook
with Workbook.create_default() as wb:
ws = wb[0]
ws.set_values("B2", [[3], [8]])
ws.add_validation(DataValidationInput(ranges="C2:C100", type=ValidationType.CUSTOM, formula1="C2<=B2*10"))
print(ws.validate_value("C2", 30).valid) # True
print(ws.validate_value("C2", 31).valid) # False
print(ws.validate_value("C3", 31).valid) # TrueCheck a value before you store it
validateValue(cell, value) tests a value against the rule that covers the cell, without writing it. The outcome has valid, the ruleId of the rule that decided, and that rule's errorStyle; a cell with no rule is valid with a null rule id. A string is always text here, even when it starts with =. Writing a cell does not check it: setValue stores any value, as Excel does when a value arrives by paste or by macro.
import createFormulon, { ComparisonOperator, ValidationErrorStyle, ValidationType } from '@libraz/formulon'
const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
const ws = wb.sheet(0)
const rule = ws.addValidation({
ranges: 'B2:B100',
type: ValidationType.Whole,
operator: ComparisonOperator.GreaterThan,
formula1: '0',
errorStyle: ValidationErrorStyle.Warning,
})
const outcome = ws.validateValue('B2', -5)
console.log(outcome.valid, outcome.ruleId === rule) // false true
console.log(outcome.errorStyle === ValidationErrorStyle.Warning) // true
console.log(JSON.stringify(ws.validateValue('Z1', -5))) // {"valid":true,"ruleId":null,"errorStyle":null}
} finally {
wb.dispose()
}from formulon import ComparisonOperator, DataValidationInput, ValidationErrorStyle, ValidationType, Workbook
with Workbook.create_default() as wb:
ws = wb[0]
rule = ws.add_validation(DataValidationInput(
ranges="B2:B100",
type=ValidationType.WHOLE,
operator=ComparisonOperator.GREATER_THAN,
formula1="0",
error_style=ValidationErrorStyle.WARNING,
))
outcome = ws.validate_value("B2", -5)
print(outcome.valid, outcome.rule_id == rule) # False True
print(outcome.error_style == ValidationErrorStyle.WARNING) # True
print(ws.validate_value("Z1", -5)) # ValidationOutcome(valid=True, rule_id=None, error_style=None)Check a number against a rule that allows 0 through 100, then write it directly to see that the cell stores it anyway.
Validate a value, then write it
A1 has a rule allowing numbers from 0 through 100. Check a candidate, then write even an out-of-range value to see validation and stored data separately.
Powered by the real Formulon engine (WASM) — it runs entirely in your browser, nothing is uploaded.
Find the cells that break their rules
getInvalidCells() lists the populated cells whose value fails the rule that covers them, in row-major order, which is Excel's Circle Invalid Data. It returns one page at a time; pass nextCursor back to read the next page, until it is null.
import createFormulon, { ComparisonOperator, ValidationType } from '@libraz/formulon'
const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
const ws = wb.sheet(0)
ws.addValidation({ ranges: 'A2:A100', type: ValidationType.List, formula1: '"Red,Green,Blue"' })
ws.addValidation({
ranges: 'B2:B100',
type: ValidationType.Whole,
operator: ComparisonOperator.Between,
formula1: '1',
formula2: '100',
})
ws.setValues('A2', [['Red', 10], ['Pink', 20], ['Blue', 500]])
const page = ws.getInvalidCells()
console.log(page.cells.map((c) => `${c.row},${c.col}=${c.value}`).join(' ')) // 2,0=Pink 3,1=500
console.log(page.nextCursor) // null
} finally {
wb.dispose()
}from formulon import ComparisonOperator, DataValidationInput, ValidationType, Workbook
with Workbook.create_default() as wb:
ws = wb[0]
ws.add_validation(DataValidationInput(ranges="A2:A100", type=ValidationType.LIST, formula1='"Red,Green,Blue"'))
ws.add_validation(DataValidationInput(
ranges="B2:B100",
type=ValidationType.WHOLE,
operator=ComparisonOperator.BETWEEN,
formula1="1",
formula2="100",
))
ws.set_values("A2", [["Red", 10], ["Pink", 20], ["Blue", 500]])
page = ws.get_invalid_cells()
print(" ".join(f"{c.row},{c.col}={c.value}" for c in page.cells)) # 2,0=Pink 3,1=500.0
print(page.next_cursor) # NonelistValidations(), updateValidation(id, patch) and removeValidation(id) read, change and remove the rules.
Filter rows with an AutoFilter
setAutoFilter places an AutoFilter on a range whose first row is the header. Each entry of columns filters one column, addressed by columnOffset from the range's first column, and its kind (FilterKind) chooses the criterion: Values keeps the listed values, Custom applies one or two comparisons, Top10 keeps the top or bottom items, and Dynamic, Color and Icon cover Excel's other filter types. The engine reads only the fields of the selected kind, so set kind together with its fields.
evaluateAutoFilter() reports which body rows pass without changing the sheet. applyAutoFilter() hides the rows that fail and shows the rest.
import createFormulon, { ComparisonOperator, FilterKind } from '@libraz/formulon'
const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
const ws = wb.sheet(0)
ws.setValues('A1', [['Item', 'Qty'], ['Bolts', 40], ['Nuts', 75], ['Washers', 5], ['Pins', 120]])
ws.setAutoFilter({
range: 'A1:B5',
columns: [{
columnOffset: 1,
kind: FilterKind.Custom,
conditions: [{ operator: ComparisonOperator.GreaterThan, value: '50' }],
}],
})
const result = ws.evaluateAutoFilter()
console.log(result.firstRow, JSON.stringify(result.match)) // 1 [false,true,false,true]
ws.applyAutoFilter()
console.log(ws.listRowOverrides().filter((r) => r.hidden).map((r) => r.row).join()) // 1,3
ws.setAutoFilter({ range: 'A1:B5', columns: [{ columnOffset: 0, kind: FilterKind.Values, values: ['Bolts', 'Pins'] }] })
console.log(JSON.stringify(ws.evaluateAutoFilter().match)) // [true,false,false,true]
} finally {
wb.dispose()
}from formulon import (
AutoFilterColumn,
AutoFilterCondition,
AutoFilterInput,
ComparisonOperator,
FilterKind,
Workbook,
)
with Workbook.create_default() as wb:
ws = wb[0]
ws.set_values("A1", [["Item", "Qty"], ["Bolts", 40], ["Nuts", 75], ["Washers", 5], ["Pins", 120]])
ws.set_auto_filter(AutoFilterInput(
range="A1:B5",
columns=[AutoFilterColumn(
column_offset=1,
kind=FilterKind.CUSTOM,
conditions=[AutoFilterCondition(ComparisonOperator.GREATER_THAN, "50")],
)],
))
result = ws.evaluate_auto_filter()
print(result.first_row, result.match) # 1 [False, True, False, True]
ws.apply_auto_filter()
print([r.row for r in ws.list_row_overrides() if r.hidden]) # [1, 3]
ws.set_auto_filter(AutoFilterInput(
range="A1:B5",
columns=[AutoFilterColumn(column_offset=0, kind=FilterKind.VALUES, values=["Bolts", "Pins"])],
))
print(ws.evaluate_auto_filter().match) # [True, False, False, True]setAutoFilter replaces the whole filter and leaves row visibility alone until applyAutoFilter() runs. clearAutoFilterCriteria() drops the criteria and shows every row but keeps the AutoFilter, and setAutoFilter(null) removes it. A table's own AutoFilter is set through its Table handle.