Custom validation message?

260 views
Skip to first unread message

Janne Anttila

unread,
Jan 19, 2017, 8:54:59 AM1/19/17
to Keystone JS
Hi,

I'm using keystone.js v0.3.22 and I would like to have custom validation for one field. For now I have added custom validation as follows:

var keystone = require('keystone');
var Types = keystone.Field.Types;


var Foo = new keystone.List('Foo');


Foo.add({
 myField
:   { type: Number, initial: true, required: true}
});


Foo.schema.path('myField').validate(function (value) {
 
return false;
}, 'myField is not valid');


Foo.register();

The problem is that instead "myField is not valid", admin UI displays generic "Validation failed" error message when creating a new item. 
If I modify existing item the message is "There was an error saving your changes: Validation failed (ValidationError)"

Can I some display custom validation messages on admin UI? 
UpdateHandler seems to have way to method to add custom validator (https://github.com/keystonejs/keystone/blob/v0.3.x/lib/updateHandler.js#L39). Can I somehow use it in this context, or is the only way to write custom field type?


Ryan Cole

unread,
Jan 24, 2017, 7:29:38 AM1/24/17
to Keystone JS
I think this is a mongoose thing right? I'd assume that errors from mongoose would bubble up to the admin UI...
Message has been deleted

Andrés Lucas

unread,
Aug 6, 2020, 11:04:09 PM8/6/20
to Keystone JS
Maybe it's too late, but on Keystone v5, there is a hook that you can add, validateInput, where you can add the resolver data as argument and an error handle. There you can return this error with a string in order to show the error message. example:



const schema = {
 fields: {
   ...other_fields,
   projectVideo: {
     type: File,
     adapter: S3FileAdapter,
     hooks: {
       beforeChange,
       validateInput: ({ resolvedData, addFieldValidationError }) => {
         if (!resolvedData.projectVideo.mimetype.match('video/'))
           return addFieldValidationError('File must be a video file type (WEBM, MP4, etc.)')
       }
     }
   },
 hooks: {
   afterDelete
 }
}



Hope this help to anyone.

Reply all
Reply to author
Forward
0 new messages