Loading session...

AI Roundtable Open Poll · 4 models

Custom eslint rule for a comment text format

Model Responses

Grok 4.20

Answer: To create a custom ESLint rule for enforcing a specific comment text format, write a JavaScript module that uses the ESLint API to scan comments and report violations when they fail to match the required pattern.

ESLint rules are plain JavaScript functions that receive a context object and return an object with AST node listeners. For comments, retrieve them via context.getSourceCode().getAllComments() inside a Program listener or similar hook, then iterate and test each comment's value against a regular expression or custom validator that matches your desired format such as requiring a ticket number prefix or specific structure. If a comment fails validation, call context.report({ node: comment, message: 'Comment must follow XYZ format' }) to surface the error. This keeps the rule focused and extensible for different formats by accepting options in the rule schema. Install the rule by placing it in a local plugins directory and referencing it in your .eslintrc.js under the rules section with the full path or as part of a custom plugin; test it using ESLint's RuleTester with sample code containing both valid and invalid comments to verify behavior.

GPT-5.4

Answer: Yes—if you need to enforce a specific comment text pattern, the right approach is to create a custom ESLint rule (or a very small local plugin), because core ESLint only offers limited generic comment controls and not arbitrary comment-content validation.

ESLint can inspect comments, but its built-in rules are not designed to enforce every possible custom text format inside comments. If your requirement is something specific—such as requiring comments to begin with a ticket ID, match a regex, use a fixed prefix, or follow a team-defined template—you will usually need a custom rule. The usual implementation is straightforward: in your rule, read all comments from `context.getSourceCode().getAllComments()`, iterate over them, and test each comment’s value against your expected format. When a comment does not match, report it with `context.report(...)`. That gives you full control over which comment types to check, which files to include, and which patterns to allow. A minimal rule typically looks like this in concept: get the source code, collect comments, skip comments you do not care about, and validate the remaining ones with a regular expression. For example, you might enforce that line comments start with `TODO(PROJ-123): ...` or that block comments include a required tag. The rule can then emit a clear lint error message explaining the expected format. If you do not want to publish a package, this can still live as a local plugin inside your repo. Many teams create an internal `eslint-plugin-*` folder and reference it from their ESLint config. That keeps the rule versioned with the codebase and makes the policy easy to maintain. Before writing a custom rule, it is worth checking whether an existing community plugin already covers your use case—especially for TODO comments, JSDoc, or license headers. But if the requirement is truly custom comment text formatting, a custom ESLint rule is the standard and most maintainable solution. In short: this is absolutely doable with ESLint, but not usually with config alone. Use a custom rule that reads comment nodes and validates their text against your format.

Claude Opus 4

Answer: You can create a custom ESLint rule that validates comment text format by leveraging ESLint's AST and the `Program` node's comments or by using comment-specific selectors in the rule visitor.

ESLint provides a powerful mechanism for creating custom rules that can inspect comments in your code. Here's how to approach it: **Accessing Comments** In modern ESLint, comments are not part of the AST nodes directly but can be accessed via `sourceCode.getAllComments()` or by using the `Program` node visitor and then calling `sourceCode.getCommentsBefore()`, `sourceCode.getCommentsAfter()`, or `sourceCode.getCommentsInside()`. You can also iterate all comments in the `Program` exit visitor. **Basic Structure of a Custom Rule** ```js module.exports = { meta: { type: 'suggestion', docs: { description: 'Enforce a specific comment text format', }, messages: { invalidFormat: 'Comment does not match the required format: {{expected}}', }, schema: [], // add options if needed }, create(context) { const sourceCode = context.getSourceCode(); return { Program() { const comments = sourceCode.getAllComments(); comments.forEach((comment) => { const value = comment.value.trim(); // Example: enforce comments start with uppercase if (value.length > 0 && /^[a-z]/.test(value)) { context.report({ loc: comment.loc, messageId: 'invalidFormat', data: { expected: 'Comment should start with an uppercase letter' }, }); } }); }, }; }, }; ``` **Key Considerations** - `comment.type` will be either `'Line'` (for `//` comments) or `'Block'` (for `/* */` comments), so you can target specific comment styles. - You can use regular expressions to enforce any format, such as TODO tags (`// TODO(username): description`), JSDoc formats, or ticket references (`// JIRA-1234: ...`). - If you want to provide auto-fixing, you can add a `fix` function in the `context.report()` call that uses `fixer.replaceTextRange()` targeting the comment's range. - For ESLint v9 flat config, use `context.sourceCode` instead of `context.getSourceCode()`. **Packaging the Rule** You can either place the rule in a local rules directory and use `--rulesdir` (deprecated) or the `eslint-plugin-rulesdir` package, or package it as a proper ESLint plugin (`eslint-plugin-your-name`) and reference it in your config. **Existing Alternatives** Before building from scratch, check if existing rules cover your needs: `eslint-plugin-eslint-comments`, the built-in `capitalized-comments`, `multiline-comment-style`, or `spaced-comment` rules may already handle common comment format requirements.

Gemini 3.1 Pro

Answer: To enforce a custom comment text format, you must create an ESLint rule that retrieves all comments via `context.getSourceCode().getAllComments()` and validates each comment's text against a regular expression.

Because ESLint does not treat comments as standard Abstract Syntax Tree (AST) nodes, standard visitor methods like `Identifier` or `CallExpression` will not catch them. Instead, your custom rule must access the entire file's comments at once by calling `getAllComments()` on the ESLint `SourceCode` object, usually within the `Program` node listener. Once you have the array of comment objects, you can iterate through them, optionally filtering by their type (such as 'Line' for single-line comments or 'Block' for multi-line comments). You then inspect the `value` property of each comment, which contains the raw text. By testing this text against a custom regular expression—for instance, ensuring that every comment starts with a capital letter, ends with a period, or includes a specific Jira ticket format—you can easily identify non-compliant strings. Finally, when a formatting violation is found, you invoke `context.report()`. By passing the comment object directly into the report function's `loc` (location) property, ESLint will accurately highlight the exact line and column of the bad comment in the developer's editor. For an enhanced developer experience, you can also attach an autofixer to the report, automatically transforming the malformed comment into the expected format.