Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attribute to Prevent Slash (/) and Backslash (\)?

I have a text field property where I do not want users to be able to enter forward or back slashes. Is there a data attribute for this or do I need to use the RegularExpression attribute?

This seems like it would be pretty common, but I am not having any luck finding the answer. I'm not familiar with Regular Expressions, so I'm researching them now.

like image 948
Josh Jay Avatar asked Dec 21 '25 05:12

Josh Jay


1 Answers

You can use the RegularExpressionAttribute for this:

[RegularExpression(@"^[^\\/]*$")]

To break the regex down:

^ ... $

The ^ and $ respectively denote the beginning and the end of the field. This wrapper forces the entire string to match the regex to validate.

[^ ... ]*

This is a negated character class that can occur zero or more times. To match, the string must not contain any of the characters inside this container.

\\
/

The first character, the backslash, must be escaped. The forward slash must not.

Once you put it all together, you have a regex that states that nowhere in the string can you have a backslash or a forward slash.


Here, try it out on Debuggex.

like image 163
Adam Maras Avatar answered Dec 24 '25 00:12

Adam Maras



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!