As far as I know, there is no way to make the Less compiler throw an error for an invalid value like described in question. However, you can make the Less compiler not to produce any output at all when an invalid value is provided by making use of the guards feature.
In the below snippet, the mixin is invoked only when either of the two valid values are passed as input. If a different value is provided, Less compiler would find no match and hence wouldn't output anything.
.box-sizing(@value){
& when (@value=content-box) , (@value=border-box){ /* comma is the or operator */
-webkit-box-sizing: @value;
-moz-box-sizing: @value;
box-sizing: @value;
}
}
#demo{
.box-sizing(content-box);
}
Less also has some built-in type functions which can be used along with guards to check if a value is valid or not (like if the input is a number or is a color etc). There is also an iskeyword
function but none of these would check for an invalid CSS value.
If you have a wide list of valid values then you could make use of the loops feature like below. Here, we extract each value from the array of valid values and if the input value matches one of them, we output the properties. If the input does not match any input value, nothing is output (again).
@valid-values: content-box, border-box, padding-box;
.box-sizing(@value){
.loop-valid-values(@index) when (@index > 0){
@valid-value: extract(@valid-values, @index);
& when (@value= @valid-value){
-webkit-box-sizing: @value;
-moz-box-sizing: @value;
box-sizing: @value;
}
.loop-valid-values(@index - 1);
}
.loop-valid-values(length(@valid-values));
}
#demo{
.box-sizing(content-box);
}
Strictly not recommended but if you insist on making the compiler throw some exception or the other when an invalid value is provided then you could deliberately introduce an error in the not-valid-value part.
.box-sizing(@value){
& when (@value= content-box), (@value= border-box){
-webkit-box-sizing: @value;
-moz-box-sizing: @value;
box-sizing: @value;
}
& when not (@value= content-box), (@value= border-box){
output: @bwahahaha; /* there is no such variable and hence when the input value is not valid, compiler will complain that variable is undefined */
}
}
#demo{
.box-sizing(conten-box);
}