Search code examples
javascriptregexcharacterlinelimit

Javascript Regex to Limit number of characters per line


I'm trying to create a JS Regular Expression to limit the amount of characters per line in an html text area. Ideally I would prefer to have it as a Javascript Regex as it's easier to use for our form validation engine.

I would like to create a regular expression that validates that a string has 10 characters per line, and a max of 3 lines

The idea would be to validate strings like the following ones:

01234567890
a
b

First line here has 11 characters so the whole string should be rejected/

a
b
c
d

This text has 4 lines so it should also be rejected.

I've tried with the following regex but is not working as expected:

^((?:\n)?[^\n]{0,10}){0,3}$

any clues on what I'm doing wrong?


Solution

  • You can use

    ^.{0,10}(?:\r?\n.{0,10}){0,2}$
    

    See the regex demo

    Details

    • ^ - start of string
    • .{0,10} - zero to ten chars other than line break chars
    • (?:\r?\n.{0,10}){0,2} - zero, one or two occurrences of
      • \r?\n - CRLF or LF line ending
      • .{0,10} - zero to ten chars other than line break chars
    • $ - end of string.

    JavaScript:

    const valid_rx = /^.{0,10}(?:\r?\n.{0,10}){0,2}$/;
    const testFunc = () => {
        if(!valid_rx.test(document.all.mytextarea.value))
        {
            console.log("Please use correct format.");
            return false;
        }
    }
    <textarea id="mytextarea" cols="50" rows="10">a
    b
    c
    </textarea>
    <button onclick="testFunc()">Click Me</button>