RegularExpression Validator in ASP.NET MVC tutorial with examples

RegularExpression Data Annotation Validator in ASP.NET MVC: A Tutorial with Code Example. Regular expressions, also known as regex, are patterns that define a specific search in a string. These patterns are used to validate, match, or extract information from a string of text. In .NET MVC, regular expressions can be used to validate user inputs in a form, for instance, to ensure that an email address entered is in the correct format. In this blog post, we will be looking at how to use regular expressions in .NET MVC for data annotation.

Data annotations in .NET MVC are used to specify validation rules for model properties. They allow you to define validation rules in one place and reuse them across your application. One of the validation attributes in .NET MVC is the RegularExpression attribute, which allows you to validate a property value based on a specified regular expression pattern.

Here is an example of how you can use the RegularExpression attribute to validate an email address in a model:
using System.ComponentModel.DataAnnotations;

public class EmailModel
    [RegularExpression(@"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$", ErrorMessage = "Invalid email format")]
    public string Email { get; set; }
@model Email

@using (Html.BeginForm())
    @Html.LabelFor(m => m.Email)
    @Html.TextBoxFor(m => m.Email)
    @Html.ValidationMessageFor(m => m.Email)
Next Step: Enable client side validation, you can check this: Enable client side validation in ASP.NET MVC

In the example above, we are using the RegularExpression attribute to define a pattern for a valid email address. The pattern ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ matches the following:
  • An email address starts with one or more characters that can be any combination of letters (upper or lowercase), numbers, dots, percent signs, plus signs, hyphens, or underscores.
  • The email address must contain an @ symbol.
  • The email address must have a domain name, which must contain one or more characters that can be any combination of letters (upper or lowercase), numbers, dots, or hyphens.
  • The email address must end with a top-level domain extension, which must be two or more letters.

If the email address entered does not match the pattern, the error message "Invalid email format" will be displayed.

In conclusion, regular expressions are a powerful tool for validating data in .NET MVC. By using the RegularExpression attribute in data annotations, you can specify validation rules for model properties, ensuring that the data entered by users is in the correct format.
Best quality Asp .Net Ajax Control Toolkit tutorials.

Give your valuable comments.

2 + 7 =

About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2024 CodingFusion
50+ C# Programs for beginners to practice