Can you restrict a string to a set of permitted strings in YANG?

67 Views Asked by At

Can we have a statement in YANG which constraints the user input string to one of the strings which are permitted? I saw that one can use pattern to match a certain regex, but what if we have strings like "apple", "orange", "strawberry" which are permitted, and the product below must be a member of this set of permissible strings?

leaf product{
  type string;
}
1

There are 1 best solutions below

2
predi On BEST ANSWER

YANG has a built-in type named enumeration, which serves the exact purpose you describe.

leaf product {
  type enumeration {
    enum apple;
    enum orange;
    enum strawberry;
  }
}

This is the type you should use if permitted values are members of a set of string constants. The specifics of the type may be found in RFC 7950, Section 9.6.

Technically speaking, you could also use the string built-in type and restrict it with a pattern that takes a regex argument such as apple|orange|strawberry, but you'd be using the wrong tool for the job.

Advantages of using enumeration instead of above:

  • the lexical representation of an enumeration value is a string - one of the enums
  • each enum may be documented with description/reference
  • each enum is (either explicitly or implicitly) assigned a value, an integer that may be used internally by implementations to identify the associated string
  • each enum may get an if-feature statement (YANG version 1.1)
  • improved readability and easier to maintain