less - Restrict mixin values and throw exception when invalid value is provided -


i have following less mixin:

.box-sizing(@value) {     -webkit-box-sizing: @value;     -moz-box-sizing: @value;     box-sizing: @value; } 

and allow values 'border-box' , 'content-box' parameter, otherwise less engine should throw exception. how can achieve this? because without validation can write value mixin , work, generate invalid css , no 1 notice there error.

as far know, there no way make less compiler throw error invalid value described in question. however, can make less compiler not produce output @ when invalid value provided making use of guards feature.

in below snippet, mixin invoked when either of 2 valid values passed input. if different value provided, less compiler find no match , hence wouldn't output anything.

.box-sizing(@value){     & when (@value=content-box) , (@value=border-box){ /* comma or operator */         -webkit-box-sizing: @value;         -moz-box-sizing: @value;         box-sizing: @value;     } } #demo{     .box-sizing(content-box); } 

less has built-in type functions can used along guards check if value valid or not (like if input number or color etc). there iskeyword function none of these check invalid css value.


if have wide list of valid values make use of loops feature below. here, extract each value array of valid values , if input value matches 1 of them, output properties. if input not match input value, nothing 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 if insist on making compiler throw exception or other when invalid value provided deliberately introduce error in 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 no such variable , hence when input value not valid, compiler complain variable undefined */     } } #demo{     .box-sizing(conten-box); } 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -