Search code examples
regexyamlgatsbynetlify-cms

How to limit the number of characters by range in `yaml` file in netlify-cms Gatsby starter


I'm using gatsby and using gatsby-starter-netlify-cms

and I'm trying to add validation for the number of characters in the widget string I have read in the docs that we can use pattern with regex to implements the validation

and here you can see how they use it

fields:
  - label: "Title"
    name: "title"
    widget: "string"
    pattern: ['.{20,}', "Must have at least 20 characters"] // this using regex
  - {label: "Layout", name: "layout", widget: "hidden", default: "blog"}
  - {label: "Featured Image", name: "thumbnail", widget: "image", required: false}
  - {label: "Body", name: "body", widget: "markdown"}
    comment: 'This is a multiline\ncomment'

so I tried to do this

    pattern: ['.{20,50}', "Must have 20 - 50 characters"]

then tried to do this

widget: "string", pattern: ['^[\s\S]{20,50}$', "Page Title should be 20-50 characters"]

any help would be appreciated


Solution

  • Try this:

    pattern: ['^.{20,50}$', "Must have at least 20 characters"]
    

    You can check how it works in RegExr (updated with the regex).

    Explanation:

    • .: any character except newline
    • ^: start of string
    • {20,50}: limit between 20 up to 50 characters
    • $: end of a string (optional in your case)