Question

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?

Was it helpful?

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)

OTHER TIPS

I think your issue is around the "-" character. Within a character set ("[xyx]"), the dash is one of the few special characters. When it comes in between two characters, it sets a range. When it has a character only on one side, it is treated simply as a dash character.

In your first regex, you end with the dash (/^[a-z0-9 ,.-]*$/gi), so it treats it as a dash character.

In your second one (/^[a-z0-9 ,.-\r]*$/gi), you end with the \r, creating a little sub-range of .-\r

You should be able to fix this by either moving the dash to the end (or beginning) of the set, or escaping it:

/^[a-z0-9 ,.\r-]*$/gi

. . . or . . .

/^[a-z0-9 ,.\-\r]*$/gi

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top