How to check string length using Hypi Directive(@length

Now, we know how to perform Mathematical operations using Math APIs.

Let’s proceed to using Hypi directives!
Hypi directives help to customise the behaviour of the data fields.

  • @ character depicts the Hypi directive. It is followed by a series of characters.
  • A directive may have a list of optional named arguments.
  • Disable directive by adding # in front of it.

In this post, we will see how to check string length using Hypi directive.
strl: String @length(min: 1, max: 5)

  • Use @length directive to perform length checks on Strings, Objects and Array fields.
  • Check if the string length or array length matches the range. min and max arguments set the length range.
  • It returns an error if the string length crosses the specified limits.
  • @length doesn’t validate data. It just checks the range limits.
  • Check if the object’s list of non-null fields matches the range.
  • A whitespace also gets added as an additional character while calculating the length of the string.

We will work with the below schema.

type DirectiveObj {
    str: String @length(min: 2, max: 5)
    str1: String @length(min: 3, max: 10)
    str2: String @length(min: 0, max: 5)
    strArray: [String] @length(min: 1, max: 5)
} 

Sample Query

Let’s add data to string fields in the DirectiveObj and check how length check works.

mutation {
  upsert(
    values: {
      DirectiveObj: {
        str: " "
        str1: "12345678901"
        str2: "1"
        strArray: ["a", "b", "c", "d", "e", "f"]
      }
    }
  ) {
    id
  }
}
#result
{
  "data": {
    "upsert": [
      {
        "id": "01FN6F0AZBHBJPFPQMNS6G3R3B"
      }
    ]
  },
  "errors": [
    {
      "message": "'DirectiveObj.str' requires at least 2, but is 1",
      "extensions": {}
    },
    {
      "message": "'DirectiveObj.str1' requires no more than 10, but is 11",
      "extensions": {}
    },
    {
      "message": "'DirectiveObj.strArray' requires no more than 5, but is 6",
      "extensions": {}
    }
  ]
} 

Check the POSTMAN collection for the @length directive in different programming languages! Click </> and choose the programming language of your choice.

Don’t forget to insert your own Authorization key and Hypi Domain under Headers to test the results!

Run in Postman