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.
As you can see, I already have the Name field requiring a value which is implemented within my model.
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.
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.
When I enter an invalid email address, it will stop me from continuing until I fix my error.
The Phone field also must receive a valid phone number.
My Web address field is also protected from invalid URLs.
Now my form contain valid data in each field and is ready to be submitted.