gregsdennis
gregsdennis

Reputation: 8428

Target specific field in Spectral schema rule

I have a rule with a schema function. The rule works fine in that it's identifying the problem, but it's also highlighting the entire object that fails the schema. Instead, I'd like it to highlight just the specific field inside the object that's causing the problem.

I've tried adding the field property, but that just causes the rule to not run (without error).

if-without-then-or-else:
  description: if requires then or else.
  severity: error
  given:
    - $
    - $..[?(@.if)]
  then:
    - function: schema
      functionOptions:
        schema:
          if:
            required:
              - if
          then:
            anyOf:
              - required: 
                - then
              - required:
                - else
{
  "if": {}
}

Upvotes: 1

Views: 283

Answers (1)

gregsdennis
gregsdennis

Reputation: 8428

I ended up inverting the schema so that it tests the other way around.

if-requires-then-or-else:
  description: 'The `if` keyword will be ignored unless an adjacent `then` and/or `else` keyword is present.'
  severity: error
  given:
    - $
    - $..[?(@.if)]
  then:
    - function: schema
      functionOptions:
        schema:
          if:
            not:
              anyOf:
                - required: 
                  - then
                - required:
                  - else
          then:
            properties:
              if: false

It's basically saying, "If either then or else are not present, then if is also disallowed.

This way, it targets the if as the thing that shouldn't be there.

Upvotes: 1

Related Questions