Search code examples
kentico-kontentkontent-ai

How can I add a validation regex to a Kontent slug element using the Kontent JS Management SDK


Hi there :) I'm struggling to add a validation regex to the URL Slug in my Content Type. I can set it manually e.g.

Manually setting validation

But I want to set it programmatically using the JS Management SDK. This is one of the things I have tried...

    const mod: ContentTypeModels.IModifyContentTypeData[] = [
        {
            op: 'addInto',
            path: '/elements/codename:page_url',
            value: {
                validation_regex: {
                    regex: '^[a-zA-Z-/]{1,60}$',
                    flags: 'i',
                    validation_message: 'URL slug must only contain (English/Latin) characters, forward slashes and hyphens',
                    is_active: true,
                },
            },
        },
    ]

That gives me the error >> Invalid operation with index '0': Unexpected path part 'codename:page_url'

In the hope that the problem is just with the path I have tried several other permutations, without success.

Is what I want possible in place i.e. without deleting and re-adding the element? And if so how?


Solution

  • The addInto operation is for adding new elements, so if there is no url slug element you can add a new one and specify the regular expression:

    [
      {    
        "op": "addInto",    
        "path": "/elements",    
        "value":{    
        "depends_on": {    
          "element": {    
            "id": "d395c03d-2b20-4631-adc6-bc4cd9c88b0b"    
          }    
        },    
        "validation_regex": {    
          "regex": "^[a-zA-Z-/]{1,60}$",    
          "flags": "i",    
          "validation_message": "URL slug must only contain (English/Latin) characters, forward slashes and hyphens",    
          "is_active": true    
        },    
        "name": "some_slug",    
        "guidelines": null,    
        "is_required": false,    
        "type": "url_slug",    
        "codename": "some_slug"    
      }    
    ]
    

    For updating just regex of existing url slug element you need to use the replace operation instead:

    [
      {
        "op": "replace",
        "path": "/elements/codename:some_type/validation_regex",
        "value":{
          "regex": "^[a-zA-Z-/]{1,60}$",
          "flags": "i",
          "validation_message": "URL slug must only contain (English/Latin) characters, forward slashes and hyphens",
           "is_active": true
        }
      }
    ]
    

    You can find more info in our API reference -> https://kontent.ai/learn/reference/management-api-v2/#operation/modify-a-content-type