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

Add additional validation rules for slugs, including lower case and valid characters #35

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,13 @@ export type PageTreeConfig = {
/* Optional field name of the language field, defaults to "language" */
languageFieldName?: string;
};
/* Optionally add any validation rules for slugs */
slugValidationOptions?: {
/* Slugs must be lowercase or fail validation */
enforceLowerCase?: boolean;
/* Slugs cannot contain invalid characters or fail validation */
enforceValidCharacters?: boolean;
}
};

/**
Expand Down
11 changes: 11 additions & 0 deletions src/validators/slug-validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,17 @@ export const slugValidator =
? `Slug must be unique. Another page with the same slug is already published, but has a draft version with a different slug: "${siblingDraftPageWithSameSlug.slug?.current}". Publish that page first or change the slug to something else.`
: 'Slug must be unique.';
}

// Additional validation rules applied if configured
// Check if slug is lowercase.
if (config.slugValidationOptions?.enforceLowerCase === true && slug?.current !== slug?.current?.toLowerCase()) {
return "Slug must be lower case.";
}

// Allow A-z, 0-9, -, ., _, ~, :, and /
if (config.slugValidationOptions?.enforceValidCharacters === true && slug?.current && /[^A-Za-z0-9\-._~:\/]/.test(slug?.current)) {
return "Slug must not contain invalid characters."
}

return true;
};