Client and Server Validation using Regular Expressions

Here are some of the regular expressions being used in the Youngevity project. These are important to prevent SQL injection attacks. These validation expressions are being used on both the Code First models and the client side Angular validation.

These are a starting point for us to start tweaking until as a team we get these expressions to a point where we are comfortable. Then it would be nice to have these as our standard regular expressions that we use on all projects thus saving us time going forward.

These expressions are using whitelisting which is just simply specifying which characters are allowed as opposed to blacklisting which specifies which characters aren’t allowed. Whitelisting is considered a best practice when writing regular expressions.

Here is an example of how to use a regular expression on a C# model:

[RegularExpression(@"^[0-9a-zA-Z /.@()!#$%^&*?+_-]+$", ErrorMessage = "Please remove invalid characters")]
        public virtual string LastName { get; set; }

Implentation using AngularJS:

<input type="text" ng-model="customerRequest.LastName" name="LastName" placeholder="* Last Name" ng-pattern="/^[0-9a-zA-Z /.@()!#$%^&*?+_-]+$/">
<div ng-show="requestForm.LastName.$error.pattern">Please remove invalid characters</div>

Basic regular expression which can be used for many different fields:

^[0-9a-zA-Z /.@()!#$%^&*?+_-]+$

Regular expression for telephone #s(this is overkill if you are just going to stick the telephone # in the database but when you need to make sure that telephone #s contain a valid 10 or 11 digit North America # it is good to use)

^D?1?D?(d{3})D?D?(d{3})D?(d{4})$

Validating string is a Guid:

^{?[dA-Fa-f]{8}-[dA-Fa-f]{4}-[dA-Fa-f]{4}-[dA-Fa-f]{4}-[dA-Fa-f]{12}}?$

This once again is just a starting point for us to have a library of regular expressions we can quickly grab when needed. For most fields the basic regular expression shown above will work in most cases. For the basic regular expression used above I intentionally did not use shortcuts that allow you to not spell out each special character which is being allowed. I like the fact that you can quickly see what the allowed special characters are without having to lookup the shortcut via google.