Skip to content

What's the best way to implement a validation that checks if two fields are the same? #714

Answered by Stranger6667
fgsch asked this question in Q&A
Discussion options

You must be logged in to vote

Hi @fgsch

I think you could make a custom keyword for this:

{
    "type": "object",
    "properties": {...}
    "same-values": ["foo", "qux"]
}

Something like this would work:

use jsonschema::{
    paths::{LazyLocation, Location},
    Keyword, ValidationError,
};
use serde_json::{json, Map, Value};

struct SameValueValidator {
   keys: Vec<String>
};

impl Keyword for SameValueValidator {
    fn validate<'i>(
        &self,
        instance: &'i Value,
        location: &LazyLocation,
    ) -> Result<(), ValidationError<'i>> {
        // TODO: Some better checking with what exact values are different?
        if !self.is_valid(instance) {
            Err(ValidationError::custom(

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Answer selected by fgsch
Comment options

You must be logged in to vote
1 reply
@Stranger6667
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants