Open fcrozatier opened 1 year ago
What do you suggest as a fix or workaround?
Well one workaround is to not use max
for textarea and use a refinement as in the repro here
https://github.com/fcrozatier/superform-textarea/blob/main/src/routes/%2Bpage.server.ts#L9
But then you also have to add a maxlength
manually.
So it's not really satisfying but at least there no browser/server validation mismatch that could confuse the end user.
Maybe there's a better approach?
I don't know, since it works in general for input fields, which are the most common case, it's probably enough to make a note in the documentation about this.
I don't know, since it works in general for input fields
Because we can't have new lines in an input field
Since this inconsistency is inevitable (html spec) and only concerns texteara because of new lines maybe it would make sense to have a .text
validation in zod? I'll ask them
But for now yeah maybe a doc note is all we can do.
Good idea, Zod is a better place for this. Thank you for making the effort! :)
I was able to get a consistent behaviour by adding a text normalisation function, like so:
/** One has to take into account the \r characters added by the new line normalization, as per html specs */
const normalise = (text: string) => text.replaceAll('\r\n', '\n');
const schema = z.object({
textarea: z.string().transform(normalise).pipe(z.string().max(5))
});
Except for Safari which correctly reports the textarea
's length with LF for new lines, but incorrectly checks against maxLength
using CRLF. Fixed by https://github.com/WebKit/WebKit/commit/2252898e2468994720be25176170e00bc7b26ca3 in Safari Technology Preview
Description As per HTML spec a
textarea
normalizes new lines to \n in the browser but to \r\n when the form is submitted. So if you insert new lines and use a naivemax
in your schema you can pass browser validation but fail server validation.This is unwanted and can be confusing for users if you have a character counter.
As an alternative one can refine the string schema, but then the constraint doesn't know about the maxlength which has to be added manually?
Refs:
If applicable, a MRE
repro repo
stackblitz https://stackblitz.com/edit/sveltekit-superforms-1-testing-xxfpiy?file=src%2Froutes%2F%2Bpage.server.ts,src%2Froutes%2F%2Bpage.svelte