chemilleX3
chemilleX3

Reputation: 1196

How to create a regex for the following scenario?

I am currently constructing my matches using regex. I wanted to accept alphanumeric and special characters like period (.), comma (,) and dash (-) only. This is my code:

code nullable: false, blank: false, maxSize: 30, matches : /^[0-9a-zA-Z,.-]+?[0-9a-zA-Z ]+?[0-9a-zA-Z,.-]*?$/

This code works fine, but every time I entered a combination of a single letter and one of the specified special characters, an error message is thrown.

Example:

1) A. (an error is thrown)
2) A- (an error is thrown)
3) A, (an error is thrown)

The above example should be a valid input. How will I trim down my regex to allow the given examples?

Upvotes: 1

Views: 257

Answers (1)

Stefan
Stefan

Reputation: 114188

A. is matched by [0-9a-zA-Z,.-]+? but the middle part [0-9a-zA-Z ]+? does't match anything.

To just match alphanumerics and period, comma and dash, /^[0-9a-zA-Z,.-]+$/ would be sufficient.

Upvotes: 2

Related Questions