feat(richtext-lexical): more lenient url validation, URL-encode invalid urls on save (#7870)
Fixes https://github.com/payloadcms/payload/issues/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
This commit is contained in:
@@ -7,7 +7,7 @@ import type {
|
||||
User,
|
||||
} from 'payload'
|
||||
|
||||
import { validateUrl } from '../../../lexical/utils/url.js'
|
||||
import { validateUrl, validateUrlMinimal } from '../../../lexical/utils/url.js'
|
||||
|
||||
export const getBaseFields = (
|
||||
config: SanitizedConfig,
|
||||
@@ -64,10 +64,20 @@ export const getBaseFields = (
|
||||
{
|
||||
name: 'url',
|
||||
type: 'text',
|
||||
hooks: {
|
||||
beforeChange: [
|
||||
({ value }) => {
|
||||
if (!validateUrl(value)) {
|
||||
return encodeURIComponent(value)
|
||||
}
|
||||
return value
|
||||
},
|
||||
],
|
||||
},
|
||||
label: ({ t }) => t('fields:enterURL'),
|
||||
required: true,
|
||||
validate: (value: string) => {
|
||||
if (!validateUrl(value)) {
|
||||
if (!validateUrlMinimal(value)) {
|
||||
return 'Invalid URL'
|
||||
}
|
||||
},
|
||||
|
||||
@@ -25,6 +25,14 @@ const absoluteRegExp =
|
||||
* */
|
||||
const relativeOrAnchorRegExp = /^[\w\-./]*(?:#\w[\w-]*)?$/
|
||||
|
||||
/**
|
||||
* Prevents unreasonable URLs from being inserted into the editor.
|
||||
* @param url
|
||||
*/
|
||||
export function validateUrlMinimal(url: string): boolean {
|
||||
return !url.includes(' ')
|
||||
}
|
||||
|
||||
// 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.
|
||||
// This is why we do not allow stuff like anchors here, as we don't want copied anchors to be turned into AutoLinkNodes.
|
||||
export function validateUrl(url: string): boolean {
|
||||
|
||||
Reference in New Issue
Block a user