Search code examples
javascriptregexcarriage-return

JavaScript Regexp - allowing carriage return lets other unwanted characters validate


I have a textarea in which i want to allow only a-z 0-9 \s .,- and \r \n

I'm using a JQuery 3rd party plugin. This is what i have for validation rules:

        jQuery("#description").validate({
        expression: "if (VAL.match(/^[a-z0-9 ,.-]*$/gi)) return true; else return false;",
        message: "Only: a-z 0-9 period comma dash space"
    });

Which works fine for a-z 0-9 ,.-

However, when i add \r within those sq.brackets it allows enter to validate which doesnt throw the message up, but the user can input any character they want and it validates. The messages show, if needed, when focus has left the textarea.

I have also added the 'm' flag for multi line and not added the \r which gave me the same effect.

Been scratching my head on this for a week, have only just started learning regexp. Does anyone have an idea which direction i should be looking in order to solve this please?


Solution

  • var string = "This is a\ntest";
    
    string.match(/^[a-z\s]$/i); // ["This is a\ntest" ]
    string.match(/^[a-z \r\n]+$/i); // ["This is a\ntest" ]
    

    You don't even need m apparently. Maybe you need to double escape your escape characters? It looks like there might be some processing going on there. So:

    string.match(/^[a-z \\r\\n]+$/i);
    

    Keep in mind that \s contains space, newline, carriage return and tab (\t)