Add date field validation

This commit is contained in:
Andrew Kingston 2021-01-28 19:41:46 +00:00
parent 58fdabe96b
commit 2db5e62e35
2 changed files with 37 additions and 10 deletions

View File

@ -12,23 +12,24 @@
let fieldApi
let value
$: fieldApi?.setValue(value)
$: flatpickrOptions = {
element: `#${$fieldState?.id}-wrapper`,
enableTime: true,
altInput: true,
altFormat: "F j Y, H:i",
}
const handleChange = event => {
const [fullDate] = event.detail
value = fullDate
}
const formatDate = dateString => {
const date = new Date(dateString)
return date.toDateString()
}
</script>
<SpectrumField {label} {field} bind:fieldState bind:fieldApi>
{#if fieldState}
<Flatpickr
{value}
options={{ element: `#${$fieldState.id}-wrapper` }}
options={flatpickrOptions}
on:change={handleChange}
element={`#${$fieldState.id}-wrapper`}>
<div
@ -47,7 +48,7 @@
aria-invalid="false"
{placeholder}
id={$fieldState.id}
value={formatDate($fieldState.value)} />
value={$fieldState.value} />
</div>
<button
type="button"

View File

@ -1,3 +1,5 @@
import flatpickr from "flatpickr"
export const createValidatorFromConstraints = (constraints, field, table) => {
let checks = []
@ -11,7 +13,7 @@ export const createValidatorFromConstraints = (constraints, field, table) => {
}
// String length constraint
if (constraints.length?.maximum) {
if (constraints.length?.maximum != null) {
const length = constraints.length?.maximum
checks.push(lengthConstraint(length))
}
@ -27,10 +29,20 @@ export const createValidatorFromConstraints = (constraints, field, table) => {
}
// Inclusion constraint
if (constraints.inclusion !== undefined) {
if (constraints.inclusion != null) {
const options = constraints.inclusion
checks.push(inclusionConstraint(options))
}
// Date constraint
if (constraints.datetime?.earliest != null) {
const limit = constraints.datetime.earliest
checks.push(dateConstraint(limit, true))
}
if (constraints.datetime?.latest != null) {
const limit = constraints.datetime.latest
checks.push(dateConstraint(limit, false))
}
}
// Evaluate each constraint
@ -51,7 +63,7 @@ const presenceConstraint = value => {
const lengthConstraint = maxLength => value => {
if (value && value.length > maxLength) {
;`Maximum ${maxLength} characters`
return `Maximum ${maxLength} characters`
}
return null
}
@ -76,3 +88,17 @@ const inclusionConstraint = (options = []) => value => {
}
return null
}
const dateConstraint = (dateString, isEarliest) => {
const dateLimit = Date.parse(dateString)
return value => {
if (value == null || value === "" || !value.length) {
return null
}
const dateValue = Date.parse(value[0])
const valid = isEarliest ? dateValue >= dateLimit : dateValue <= dateLimit
const adjective = isEarliest ? "Earliest" : "Latest"
const limitString = flatpickr.formatDate(new Date(dateLimit), "F j Y, H:i")
return valid ? null : `${adjective} is ${limitString}`
}
}