Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Best way to validate optional ISO time #682

Closed
zettadam opened this issue Jun 29, 2024 · 2 comments
Closed

Best way to validate optional ISO time #682

zettadam opened this issue Jun 29, 2024 · 2 comments
Assignees
Labels
question Further information is requested

Comments

@zettadam
Copy link

zettadam commented Jun 29, 2024

What is the best way to validate optional ISO time?

When I write schema like this in the Playground:

import * as v from 'valibot'
const Schema = v.pipe(
    v.string(),
    v.union([
        v.literal(''),
        v.isoTime('Invalid time format')
    ])
)
const result = v.safeParse(Schema, '08:34')

console.log('result', result)

I receive cryptic errors.

When I copy this code into my editor, I receive cryptic TS errors related to union.

@zettadam
Copy link
Author

zettadam commented Jun 29, 2024

I have come up with this function which passed all tests I had written so far:

export function validateTime(config: Config) {
  // defaults
  const _required = config.required ?? !config.optional ?? false

  return pipe(
    string(),
    !_required ? minLength(0) : nonEmpty('Required field'),
    check((input) => {
      if (!_required && !input) return true
      return /^(?:0\d|1\d|2[0-3]):[0-5]\d$/u.test(input)
    }, 'Invalid time format'),
  )
}

But I'd rather use check as a last resort.

@fabian-hiller
Copy link
Owner

Here are two examples:

import * as v from 'valibot';

// Time or undefined
const Schema1 = v.optional(v.pipe(v.string(), v.isoTime()));

// Time or empty string
const Schema2 = v.union([v.literal(''), v.pipe(v.string(), v.isoTime())]);

@fabian-hiller fabian-hiller self-assigned this Jun 29, 2024
@fabian-hiller fabian-hiller added the question Further information is requested label Jun 29, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants