验证器是一个JavaScript函数,它只接受要验证的值作为输入,因此不允许将该值与另一个单元格的值进行比较.
要仅验证整数值,可以稍微修改hot_validate_numeric
.这就是我所做的(但我没有测试):
hot_validate_integer <- function (hot, cols, min = NULL, max = NULL, choices = NULL,
exclude = NULL, allowInvalid = FALSE)
{
f <- paste(
"function (value, callback) {",
" if (value === null || value === void 0) {",
" value = '';",
" }",
" if (this.allowEmpty && value === '') {",
" return callback(true);",
" } else if (value === '') {",
" return callback(false);",
" }",
" let isNumber = /^-?\\d*(\\.|,)?\\d*$/.test(value);",
" if (!isNumber) {",
" return callback(false);",
" }",
" let x = parseFloat(value);",
" if (isNaN(x) || !Number.isInteger(x)) {",
" return callback(false);",
" }",
" %exclude",
" %min",
" %max",
" %choices",
" return callback(true);",
"}",
sep = "\n"
)
if (!is.null(exclude))
ex_str = paste0("if ([", paste0(paste0("'", exclude,
"'"), collapse = ","), "].indexOf(value) > -1) { return callback(false); }")
else ex_str = ""
f = gsub("%exclude", ex_str, f)
if (!is.null(min))
min_str = paste0("if (value < ", min, ") { return callback(false); }")
else min_str = ""
f = gsub("%min", min_str, f)
if (!is.null(max))
max_str = paste0("if (value > ", max, ") { return callback(false); }")
else max_str = ""
f = gsub("%max", max_str, f)
if (!is.null(choices))
chcs_str = paste0("if ([", paste0(paste0("'", choices,
"'"), collapse = ","), "].indexOf(value) == -1) { return callback(false); }")
else chcs_str = ""
f = gsub("%choices", chcs_str, f)
for (x in cols) hot = hot %>% hot_col(x, validator = f, allowInvalid = allowInvalid)
hot
}
Edit: it's possible!
最后,可以使用afterValidateCell
钩子与上面的单元格进行比较:
jsCode <- c(
"function(el, x) {",
" var hot = this.hot;",
" Handsontable.hooks.add('afterValidate', function(isValid, value, row, prop){",
" if(row > 0) {",
" let x = this.getDataAtCell(row - 1, prop);",
" if(value < x) {",
" return(false);",
" }",
" }",
" }, hot);",
"}"
)
library(rhandsontable)
library(htmlwidgets)
MAT = matrix(seq_len(50), nrow = 10, dimnames = list(LETTERS[1:10],
letters[1:5]))
rhandsontable(MAT) %>%
hot_validate_integer(col = 1) %>%
onRender(jsCode)