Skip to content

Instantly share code, notes, and snippets.

@aruis
Created February 20, 2019 06:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aruis/d4a28b3cedfcc2a23a85ac67ca68adb7 to your computer and use it in GitHub Desktop.
Save aruis/d4a28b3cedfcc2a23a85ac67ca68adb7 to your computer and use it in GitHub Desktop.
def rules = [
[
"expression": ' v_name != null && v_name.length()>0 ',
"tip" : "姓名必填"
],
[
"target" : ['v_password', 'v_password_twice'],
"expression": ' v_password == v_password_twice ',
"tip" : "两次密码必须一致"
]
]
def map = [
"v_name" : '',
"v_password" : "abc",
"v_password_twice": "abc",
]
def check(List rules, def map) {
def sharedData = new Binding()
def shell = new GroovyShell(sharedData)
sharedData.setProperty("length", { s ->
if (s == null) return 0
return s.length()
})
map.each { k, v ->
sharedData.setProperty(k, v)
}
rules.findAll { !shell.evaluate(it.expression) }
}
check(rules, map).each {
println(it.tip)
}
@xrwang8
Copy link

xrwang8 commented Jun 27, 2021

sharedData.setProperty("length", { s ->
if (s == null) return 0
return s.length()
})
map.each { k, v ->
sharedData.setProperty(k, v)
}
这一步没看懂

@aruis
Copy link
Author

aruis commented Jun 28, 2021

@xrwang8 你好

map.each { k, v ->
    sharedData.setProperty(k, v)
}

这段的意思是把map里的数据,塞到一个沙盒里,这样沙盒在运行rules里吗的expression 时,才能认识map里面的数据

sharedData.setProperty("length", { s ->
    if (s == null) return 0
    return s.length()
})

这个是举个例子,除了往沙盒里面放数据(比如map的数据放进去了),还可以往沙盒里面塞方法。塞的方法,可以在expression里面这样用:

def rules = [
        [
                "expression": ' v_name != null && length(v_name)>0  ',
                "tip"       : "姓名必填"
        ]
]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment