question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to support empty strings for z.string().datetime({ offset: true }).nullish()

See original GitHub issue

How to support empty strings for z.string().datetime({ offset: true }).nullish() schema if the string value is empty, I want it converted to null or keep the original value ie., ""

the following code throw error

import { afterAll, beforeAll } from 'vitest';
import { z } from 'zod';


describe('Test zod validations', () => {

	it('should correctly handles a valid ISO date-string', () => {
		const valid_from = '2022-12-14T22:07:10.430805+00:00';
		const valid_to = undefined; <-- this works
                 const valid_to = null; <-- this works
                 const valid_to =""; <-- this is not working


		const schema = z.string().datetime({ offset: true }).nullish();

		expect(schema.parse(valid_from)).toStrictEqual(valid_from);
		expect(schema.parse(valid_to)).toStrictEqual(valid_to);
	});
});

ERROR

ZodError: [
  {
    "code": "invalid_string",
    "validation": "datetime",
    "message": "Invalid datetime",
    "path": []
  }
]


Serialized Error: {
  "addIssue": "Function<>",
  "addIssues": "Function<>",
  "errors": [
    {
      "code": "invalid_string",
      "message": "Invalid datetime",
      "path": [],
      "validation": "datetime",
    },
  ],
  "flatten": "Function<flatten>",
  "formErrors": {
    "fieldErrors": {},
    "formErrors": [
      "Invalid datetime",
    ],
  },
  "format": "Function<format>",
  "isEmpty": false,
  "issues": [
    {
      "code": "invalid_string",
      "message": "Invalid datetime",
      "path": [],
      "validation": "datetime",
    },
  ],
}

Issue Analytics

  • State:open
  • Created 9 months ago
  • Comments:8 (1 by maintainers)

github_iconTop GitHub Comments

2reactions
samchungycommented, Dec 21, 2022

I think the workarounds are sufficient here. I don’t think any of the other string validators would accept an empty string as a valid option.

You wouldn’t consider an empty string as a valid date

1reaction
xmlkingcommented, Dec 20, 2022

Wish we have built-in z.nuller like z.coerce

z.nuller.string().datetime({ offset: true }).nullish()

My reusable solution:

export function emptyToNull(arg: unknown) {
	if (typeof arg !== 'string') {
		return arg;
	}
	if (arg.trim() === '') {
		return null;
	}
	return arg;
}


const valid_to = '';
const emptySchema = z.preprocess(emptyToNull, z.string().datetime({ offset: true }).nullish());
expect(emptySchema.parse(valid_to)).toStrictEqual(null);

another workaround:

const emptySchema =  z.string().datetime({ offset: true }).nullish().catch(null);
Read more comments on GitHub >

github_iconTop Results From Across the Web

colinhacks/zod: TypeScript-first schema validation ... - GitHub
The z.string().datetime() method defaults to UTC validation: no timezone offsets with arbitrary sub-second decimal precision.
Read more >
github.com-colinhacks-zod_-_2022-12-13_08-31-01
Timezone offsets can be allowed by setting the offset option to true . ```tsconst datetime = z.string().datetime({ offset: true });.
Read more >
c# - Allow empty strings for fields marked with PhoneAttribute ...
Use following two data annotations: [Required(AllowEmptyStrings = true)] [DisplayFormat(ConvertEmptyStringToNull = false)].
Read more >
Nullish Coalescing Operator (??) In JavaScript - What Is It And ...
This type of operator is handy when we want falsy values like 0 (zero) or empty strings ('' or "") to be valid...
Read more >
VRL example reference | Vector documentation
The vector vrl command has many other capabilities, run the command using vector vrl --help to see more information. Real world examples. Parse...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found