Getting the current user inside validation for applying different validation rules based on user roles.

6 replies
Last updated: Jul 26, 2022
Hallo guys, is there any way to get the current user inside validation? Thinking about apply different validation rules for different users with different roles.
Jul 26, 2022, 2:26 AM
I think this is possible. Validation has the ability to allow custom validation rules and async operations, and the current user store is part of the JS client and should expose the default roles, e.g: https://www.sanity.io/schemas/initial-value-template-with-current-user-4449e575

N.B.: There's a warning at the end of the validation doc that validation happens on every field change but I think it applies more to truly external APIs (like not getting rate limited trying to get a stock price because you typed a sentence and rang up fifty requests in a few seconds =)
Jul 26, 2022, 2:41 AM
Thanks for the reply and I had a try but getting some error, you can see the screenshot.
Jul 26, 2022, 2:53 AM
That's an interesting error; I am not sure what the type is for validation; I'd assume an object, but I thought I'd give it a try myself. Outside the schema at the top of the file I wrote

const getUser = async () => {
    const userObject = await userStore.getUser('me')
    if (userObject) {
        return userObject
    }
}
and then under my array field, I wrote


validation: Rule => Rule.required().custom(value => {
                return getUser().then(user => {
                    if (user.displayName === 'Vincent Florio') {
                        return true
                    } else {
                        return 'It isn't Vincent'
                    }
                })
            }),
and it worked as you'd expect. No errors if I was me (I am) but as a test I inverted the check to be
!== and got my message as a validation warning.
I make no claim that it's performant or a good way to do it, but it functions as a proof of concept.
Jul 26, 2022, 4:02 AM
Jul 26, 2022, 4:03 AM
Cool many thanks for the help πŸ‘
Jul 26, 2022, 5:32 AM
I'm asking that because in sanity if we set a max rule for the array, the "add item" button would be disabled if there's already 2 items and that could prevent user clicking that button
Jul 26, 2022, 5:40 AM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?