Skip to content

Commit ad7a387

Browse files
authored
feat(richtext-lexical): more lenient url validation, URL-encode invalid urls on save (#7870)
Fixes #7477 This simplifies validation to the point where it only errors on spaces. Actual validation is then used in beforeChange, which then automatically url encodes the input if it doesn't pass
1 parent d05be01 commit ad7a387

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

packages/richtext-lexical/src/features/link/server/baseFields.ts

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import type {
77
User,
88
} from 'payload'
99

10-
import { validateUrl } from '../../../lexical/utils/url.js'
10+
import { validateUrl, validateUrlMinimal } from '../../../lexical/utils/url.js'
1111

1212
export const getBaseFields = (
1313
config: SanitizedConfig,
@@ -64,10 +64,20 @@ export const getBaseFields = (
6464
{
6565
name: 'url',
6666
type: 'text',
67+
hooks: {
68+
beforeChange: [
69+
({ value }) => {
70+
if (!validateUrl(value)) {
71+
return encodeURIComponent(value)
72+
}
73+
return value
74+
},
75+
],
76+
},
6777
label: ({ t }) => t('fields:enterURL'),
6878
required: true,
6979
validate: (value: string) => {
70-
if (!validateUrl(value)) {
80+
if (!validateUrlMinimal(value)) {
7181
return 'Invalid URL'
7282
}
7383
},

packages/richtext-lexical/src/lexical/utils/url.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,14 @@ const absoluteRegExp =
2525
* */
2626
const relativeOrAnchorRegExp = /^[\w\-./]*(?:#\w[\w-]*)?$/
2727

28+
/**
29+
* Prevents unreasonable URLs from being inserted into the editor.
30+
* @param url
31+
*/
32+
export function validateUrlMinimal(url: string): boolean {
33+
return !url.includes(' ')
34+
}
35+
2836
// Do not keep validateUrl function too loose. This is run when pasting in text, to determine if links are in that text and if it should create AutoLinkNodes.
2937
// This is why we do not allow stuff like anchors here, as we don't want copied anchors to be turned into AutoLinkNodes.
3038
export function validateUrl(url: string): boolean {

0 commit comments

Comments
 (0)