0

I am not very good at regular expressions so maybe this is a simple question, but I am certainly missing something. I use regular expressions to validate specific input from user. The input must be accepted (regex must match) if and only if the input string contains no commas and no whitespaces(in other words, the input must be single word without commas). Except that, it can contain any symbols and the input string can have any length. Now, when I use this regular expression, it matches input, that doesn't contain commas.

/^[^,]*$/

I wanted to add the whitespace part to it, so I made this expression

/^[^,\s]*$/

which behaves in a very weird way. It does what it should except one thing. For some reasons, it matches(and lets in) strings, that end with space (If they end with comma, everything is OK and it doesn't match). I dont wan't it to match strings with trailing whitespaces but I don't know, how to adjust the regular expression to do this. So my questions are - why is this weird thing happening and how to change the regular expression to do what it should.

here is an example: http://jsbin.com/qoyoyagilo/2/edit?html,js,output

What is even weirder, when I tried my regex on rubular, it didn' t match strings with trailing whitespaces. I am starting to believe, that this has to do something with javascript and not with my particular regex

0

1 Answer 1

0

Angular already trims your strings before validating them and binding to model. Extra whitespace at the beginning and at the end of strings won't even be matched against your regular expression (or any other validator).

You can use ng-trim="false" if you wish to disable this behavior:

<input ng-model="yourmodelvar" ng-trim="false" ng-pattern="[^,\s]*">

Also note that you don't need the ^ and $ chars in your regexp, since validation is performed against the whole string automatically. From the documentation on ng-pattern:

Sets pattern validation error key if the ngModel $viewValue value does not match a RegExp found by evaluating the Angular expression given in the attribute value. If the expression evaluates to a RegExp object, then this is used directly. If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it in ^ and $ characters. For instance, "abc" will be converted to new RegExp('^abc$').

References:

Sign up to request clarification or add additional context in comments.

2 Comments

ah, sorry I had no idea about this, I was searching for the problem in regex and angular was actually solving my problem without me noticing.
I should have seen the duplicate, anyway :/.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.