improve validation schema (#3984)

This commit is contained in:
pablonyx 2025-02-17 19:18:23 -08:00 committed by GitHub
parent 0826b035a2
commit e3bc7cc747
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 32 additions and 12 deletions

View File

@ -111,9 +111,15 @@ export default function CreateCredential({
const { name, is_public, groups, ...credentialValues } = values;
const filteredCredentialValues = Object.fromEntries(
Object.entries(credentialValues).filter(
([_, value]) => value !== null && value !== ""
)
);
try {
const response = await submitCredential({
credential_json: credentialValues,
credential_json: filteredCredentialValues,
admin_public: true,
curator_public: is_public,
groups: groups,

View File

@ -6,18 +6,32 @@ import {
getDisplayNameForCredentialKey,
} from "@/lib/connectors/credentials";
export function createValidationSchema(json_values: dictionaryType) {
const schemaFields: { [key: string]: Yup.StringSchema } = {};
export function createValidationSchema(json_values: Record<string, any>) {
const schemaFields: Record<string, Yup.AnySchema> = {};
for (const key in json_values) {
if (Object.prototype.hasOwnProperty.call(json_values, key)) {
if (json_values[key] === null) {
schemaFields[key] = Yup.string().optional();
} else {
schemaFields[key] = Yup.string().required(
`Please enter your ${getDisplayNameForCredentialKey(key)}`
);
if (!Object.prototype.hasOwnProperty.call(json_values, key)) {
continue;
}
const displayName = getDisplayNameForCredentialKey(key);
if (json_values[key] === null) {
// Field is optional:
schemaFields[key] = Yup.string()
.trim()
// Transform empty strings to null
.transform((value) => (value === "" ? null : value))
.nullable()
.notRequired();
} else {
// Field is required:
schemaFields[key] = Yup.string()
.trim()
// This ensures user cannot enter an empty string:
.min(1, `${displayName} cannot be empty`)
// The required message is shown if the field is missing
.required(`Please enter your ${displayName}`);
}
}