RegularExpression Data Annotation attribute in MVC3 Razor

  1. Regular expressions are an efficient and terse means to enforce the shape and contents of a string value.
  2. Using this attribute we can specify a regular expression, and enforce string value to adhere to the expression.
  3. If string value is not in accordance to regular expression, validation message is shown.
  4. The Regular expression attribute is usually used to validate Email formats.

Example 1 :


In the above we have applied a format of Email to accept using RegularExpression attribute. We have not supplied the error message to show, it will pick the default message to show on UI.



Example 2 :


In the above example, along with the regular expression we have also specified the error message to show on UI when validation fails.

UI :



Example 3 :


In above example, we are picking the error message from Resource file. The above code accepts to have a resource file with name Multi with key Email_Format.

Resource :


UI :


Example 4 :

We can also use this attribute to validate fields other than Email. In the above we are using RegularExpression attribute to ensure LastName will accept only string value. 

UI :


In the above scenario, we input integers in the LastName field. It gave the error as it is against out Regular Expression applied for LastName property.


Watch Video :


0 comments:

Post a Comment