MVC: Regular Expressions

Please see my other MVC articles.

Enforcing valid formats on user input.

Most user-input forms’ business rules indicate specific formats for the data they receive.
MVC enables developers to enforce those rules very easily by using regular expression within their custom models.

To illustrate this feature, I will begin with a simple Create form.

1-mvc-regular-expressions

As you can see, I already have the Name field requiring a value which is implemented within my model.

2-mvc-regular-expressions

3-mvc-regular-expressions

However, I want to ensure that my Email Address field only receives a valid email address or presents an appropriate error message.
Therefore, I will implement a regular expression which enforces the rule.
Similarly, I am going to implement another regular expression for my Phone field to ensure what the user enters in a valid format.

5-mvc-regular-expressions

Finally, I am going to protect my Web Address field to that users won’t enter invalid URLs by adding a regular expression to its field in the model.

Now when a user fills out the form, it will only allow them to submit when they enter the data in a format I prescribe.
For example, the Name field will only allow the user to enter 1-25 characters in length.

7-mvc-regular-expressions

When I enter an invalid email address, it will stop me from continuing until I fix my error.

8-mvc-regular-expressions

9-mvc-regular-expressions

The Phone field also must receive a valid phone number.

10-mvc-regular-expressions

11-mvc-regular-expressions

My Web address field is also protected from invalid URLs.

12-mvc-regular-expressions 13-mvc-regular-expressions

Now my form contain valid data in each field and is ready to be submitted.

14-mvc-regular-expressions

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s