Skip to content

Commit

Permalink
fix(ObjectType): fix required message for properties not being replaced
Browse files Browse the repository at this point in the history
  • Loading branch information
simonguo committed Apr 12, 2024
1 parent c349fe7 commit 7f7332d
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 2 deletions.
3 changes: 3 additions & 0 deletions .codesandbox/ci.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"sandboxes": ["new"]
}
4 changes: 2 additions & 2 deletions src/ObjectType.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export class ObjectType<DataType = any, E = ErrorMessageType> extends MixedType<
if (type.required && !checkRequired(value, type.trim, type.emptyAllowed)) {
return {
hasError: true,
errorMessage: formatErrorMessage<E>(this.requiredMessage || this.locale.isRequired, {
errorMessage: formatErrorMessage<E>(type.requiredMessage || type.locale?.isRequired, {
name: type.fieldLabel || childFieldKey || fieldName
})
};
Expand Down Expand Up @@ -75,7 +75,7 @@ export class ObjectType<DataType = any, E = ErrorMessageType> extends MixedType<
if (type.required && !checkRequired(value, type.trim, type.emptyAllowed)) {
return Promise.resolve({
hasError: true,
errorMessage: formatErrorMessage<E>(this.requiredMessage || this.locale.isRequired, {
errorMessage: formatErrorMessage<E>(type.requiredMessage || type.locale?.isRequired, {
name: type.fieldLabel || childFieldKey || fieldName
})
});
Expand Down
7 changes: 7 additions & 0 deletions src/Schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,13 @@ export class Schema<DataType = any, ErrorMsgType = string> {
return Object.keys(this.$spec);
}

/**
* Get the schema specification
*/
getSchemaSpec() {
return this.$spec;
}

checkForField<T extends keyof DataType>(
fieldName: T,
data: DataType,
Expand Down
24 changes: 24 additions & 0 deletions test/ObjectTypeSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -323,4 +323,28 @@ describe('#ObjectType', () => {
const result = await schema.checkAsync({ user: null });
expect(result).to.deep.equal({ user: { hasError: false } });
});

it('Should replace default required message', () => {
const schema = new Schema({
user: ObjectType().shape({
email: StringType().isEmail().isRequired('Email is required')
})
});

const result = schema.check({ user: { email: '' } });

expect(result.user.object.email.errorMessage).to.equal('Email is required');
});

it('Should replace default required message with async', async () => {
const schema = new Schema({
user: ObjectType().shape({
email: StringType().isEmail().isRequired('Email is required')
})
});

const result = await schema.checkAsync({ user: { email: '' } });

expect(result.user.object.email.errorMessage).to.equal('Email is required');
});
});

0 comments on commit 7f7332d

Please sign in to comment.