Compile Regex Once With sync.OnceValue
Defer compiling a regexp until first validation with sync.OnceValue, so concurrent goroutines share one compiled matcher without manual locks.
Validate user input before it reaches your business logic.
201 published examples — showing latest 48
Defer compiling a regexp until first validation with sync.OnceValue, so concurrent goroutines share one compiled matcher without manual locks.
Enable setParseBigDecimal(true) on DecimalFormat with ParsePosition checks so long grouped decimals parse without Double rounding or tail junk.
Query LocalDate.range(ChronoField.DAY_OF_MONTH) to inspect month-specific ValueRange bounds and validate candidate days before construction.
Pass a helper function to V8 Error.captureStackTrace so custom validation errors trim internal helper frames and highlight the caller site first.
Resolve the grammatical plural form of a numeric span with Intl.PluralRules.selectRange across locales instead of guessing from the upper bound alone.
Parse UTC Z timestamps, compact dates, and ISO week strings via Python 3.11 datetime.fromisoformat, rejecting naive timestamps without tzinfo.
Check numeric arguments with numbers.Integral and numbers.Real across int, float, and Fraction while explicitly rejecting bool subclasses of int.
Implement TryFrom<&str> and TryFrom<String> for trimmed non-empty domain newtypes, rejecting blank or oversized inputs with typed validation errors.
Pair Intl.PluralRules ordinal selection with a typed lookup table requiring an other fallback so rank formatting handles 1st, 2nd, 3rd, and 11th accurately.
Build a mapped union helper RequireAtLeastOne<T, K> so callers must supply at least one optional identifier key while rejecting empty objects at compile time.
List the ISO country and language codes the JDK knows with getISOCountries and getISOLanguages, then validate user input against those sets.
Transform wrapped values with map and keep the Optional flat with flatMap, so parsing and validation steps compose without nested wrappers.
Bound values with Math.min and Math.max — empty calls return the infinities, any NaN poisons the result, and nesting the two builds a clamp.
Parse numeric strings with parseFloat and parseInt, which tolerate trailing garbage where Number() rejects it — choose deliberately per input source.
Gate input by character class with isalpha, isalnum, and isspace — all three return False for empty strings, so strip before judging user input.
Validate routing prefixes with str.startswith, which accepts a tuple of candidates and a start offset so one call replaces or-ed comparisons.
Flip letter case in place with str.swapcase and gate display rules with istitle, isupper, and islower, which all return False for empty or digit-only strings.
Match whole strings with SIMILAR TO, which keeps LIKE wildcards but adds POSIX alternation, repetition, and bracket classes — while the dot stays literal.
The details toggle event arrives as a plain Event, so handlers cast to ToggleEvent once and read newState, oldState, and the open flag with full types.
HTMLInputElement.setRangeText replaces a character range with four selection modes, and omitting start and end targets the current user selection instead.
Write struct fields by name with reflect.Value.FieldByName after CanSet and AssignableTo checks, so generic form or config binding fails with clear errors.
Accept month names in any letter case by building a DateTimeFormatter with parseCaseInsensitive instead of upper-casing the input yourself first.
The default percent instance rounds to whole percents; setMaximumFractionDigits restores decimals and parse turns 43.21% back into the ratio 0.4321.
The for attribute and label wrapping both connect a label to its control; element.labels stays live and htmlFor re-points the association on assignment.
getModifierState('CapsLock') reports the physical lock state at keydown time, so password fields can surface a caps-lock hint without tracking keyup.
form.reset() restores controls natively but custom UI state is yours; the reset event runs before the revert, so deferred reads see the restored values.
inputMode picks the virtual keyboard layout and enterKeyHint labels the action key, taming mobile form fields without changing the input type.
The invalid event fires per failing control and does not bubble, so a form-level listener uses capture to route validationMessage into field slots.
ParseForm decodes an application/x-www-form-urlencoded body so repeated keys become string slices and Form.Get returns the first submitted value.
Check whether two inclusive date ranges overlap with a two-comparison rule covering containment, adjacency, and disjoint spans.
parseBest tries queries from most to least complete: an optional-section formatter parses timestamps, datetimes, and date-only strings without try/catch chains.
Validate user emails with a conservative regex pattern that accepts common shapes and rejects spaces or missing domains.
Case conversion changes meaning under the Turkish locale, so fixed words like protocol names must pin Locale.ROOT instead of trusting the default.
Fold fullwidth Latin, superscript digits, and ligatures to base letters with NFKC before validating input, so length checks see real characters.
PatternSyntaxException reports the failing index and a description, so a regex built from user input can reject bad patterns without guessing.
Pattern.CANON_EQ matches precomposed and decomposed accents as equal, so café with a combining mark still finds the precomposed pattern.
Pasted text hides U+200B and U+FEFF characters that trim and strip keep: drop code points whose Unicode category is FORMAT to clean them reliably.
Cut long text to a code point budget before appending an ellipsis, so surrogate pairs and CJK characters never split mid-character.
Keep a select-all checkbox truthful: indeterminate marks partial selection while checked stays binary, and aria-checked mixed exposes the third state.
Hook the formdata event to append computed fields onto the entry list right before submission, without adding invisible inputs to the markup.
Turn keydown events into actions with a hotkey map; modifier keys join the combination and text inputs plus IME composition are skipped.
setCustomValidity attaches a custom message that fails validity until cleared with an empty string, covering rules the built-in constraints cannot express.
Move a text field caret or preselect a span with setSelectionRange after programmatic writes, and read selectionStart, selectionEnd, selectionDirection back.
In bubbling event.target stays at the element actually hit while event.currentTarget names the element running the listener, enabling one delegated handler.
Node.contains answers whether one node sits inside another, inclusive of itself, which is the check a click-outside handler needs before closing a menu.
len on str counts code points while len of the UTF-8 encoding counts bytes, so the same text reports different sizes at the language and transport layers.
findall returns plain strings for one capture group but tuples once two or more groups appear, a shape change that trips naive parsers.
Annotated attaches validation markers next to field types, and get_type_hints with include_extras recovers them for runtime checks.
Showing 48 of 201 verified Form Validation examples. Filter the full catalog by language, framework, or keyword in Explore.
Browse & filter all 201 examples in Explore →