pat*_*ryk 3 javascript forms validation lint codemirror
我正在使用很棒的CodeMirror库.我正在实现的代码编辑器是表单的一部分,因此我想用linting进行基本检查,看看用户的输入是否有效.除非代码没问题,否则我不想处理表单.
所以问题是:CodeMirror编辑器实例上是否有一个方法可以让我检索linting的结果?我正在查看文档和Google,但未能找到任何有用的信息.这种performLint方法被添加到编辑器中,但它不会返回linting的结果.
小智 6
没有特定的方法来获取linting结果,但是getAnnotations在lint选项对象中定义属性时会提供一个钩子.
这是一个触发linting的基本选项对象:
var codeMirrorOptions = {
"lineNumbers": true,
"indentWithTabs": true,
"mode": "css",
"gutters": ['CodeMirror-lint-markers'],
"lint": true
}
Run Code Online (Sandbox Code Playgroud)
您可以指定一个对象(而不是布尔值)作为lint属性:
"lint": {
"getAnnotations": css_validator,
"async": true
}
Run Code Online (Sandbox Code Playgroud)
然后,定义自己的验证器函数.此函数只能调用CodeMirror的捆绑验证器:
function css_validator(cm, updateLinting, options) {
// call the built in css linter from addon/lint/css-lint.js
var errors = CodeMirror.lint.css(cm);
updateLinting(errors);
}
Run Code Online (Sandbox Code Playgroud)
此时你已经复制了lint:true的行为 - 但现在该errors变量包含一个lint错误数组.如果errors.length == 0没有发现错误.
注意:此示例假定您正在使用CSS,但同样适用于其他类型.
小智 5
lint.js 中的 updateLinting 函数将其注释(和编辑器)传递给 onUpdateLinting 选项:
if (options.onUpdateLinting) options.onUpdateLinting(annotationsNotSorted, annotations, cm);
Run Code Online (Sandbox Code Playgroud)
所以你所要做的就是让你的处理程序作为 lint 选项属性:
lint: { onUpdateLinting: handleErrors }
Run Code Online (Sandbox Code Playgroud)