Data annotation attributes

15 Mar 202420 minutes to read

The DataForm component enables users to define the data annotation attributes available from the instance of System.ComponentModel.DataAnnotations.

Display attribute

The DisplayAttribute class is used to specify the display name for a property. The display name is used as the label for the corresponding editor in the DataForm component if label text is not specified for the form item.

Name property

The Name property is used to specify the display name for a property. The display name is used as the label for the corresponding editor in the DataForm component if label text is not specified for the form item.

[Display(Name = "First Name")]
public string FirstName { get; set; }

Short name property

The ShortName property is used to specify the short display name for a property. The short display name is used as the label for the corresponding editor in the DataForm component if label text is not specified for the form item.

[Display(ShortName = "First Name")]
public string FirstName { get; set; }

NOTE

DataForm gives priority to the ShortName property over the Name property of DisplayAttribute and LabelText property of the FormItem.

Prompt property

The Prompt property is used to specify the prompt for a property. The prompt is used as the placeholder for the corresponding editor in the DataForm component.

[Display(Prompt = "Enter your first name")]
public string FirstName { get; set; }

Auto generate field property

The AutoGenerateField property is used to specify whether the property should be automatically generated as a field in the DataForm component.

[Display(AutoGenerateField = false)]
public string ID { get; set; }

Validation attributes

The DataForm component supports the following validation attributes from the System.ComponentModel.DataAnnotations namespace.

Required attribute

The RequiredAttribute class is used to specify that a property is required. The DataForm component displays an error message if the property is empty.

[Required(ErrorMessage = "Name is required")]
public string Name { get; set; }

Range attribute

The RangeAttribute class is used to specify the numeric range constraints for the value of a property. The DataForm component displays an error message if the property value is not within the specified range.

[Range(0, 100, ErrorMessage = "Age must be between 0 and 100")]
public int Age { get; set; }

Regular expression attribute

The RegularExpressionAttribute class is used to specify that a property value must match a specified regular expression. The DataForm component displays an error message if the property value does not match the specified regular expression.

[RegularExpression(@"^[a-zA-Z]+$", ErrorMessage = "Name must contain only alphabets")]
public string Name { get; set; }

String length Attribute

The StringLengthAttribute class is used to specify the minimum and maximum length constraints for the value of a property. The DataForm component displays an error message if the property value is not within the specified length constraints.

[StringLength(100, MinimumLength = 3, ErrorMessage = "Name must be between 5 and 10 characters")]
 public string Name { get; set; }

Minimum length Attribute

The MinLengthAttribute class is used to specify the minimum length constraints for the value of a property. The DataForm component displays an error message if the property value is not within the specified length constraints.

[MinLength(3, ErrorMessage = "Name must be at least 3 characters")]
public string Name { get; set; }

Maximum length Attribute

The MaxLengthAttribute class is used to specify the maximum length constraints for the value of a property. The DataForm component displays an error message if the property value is not within the specified length constraints.

[MaxLength(10, ErrorMessage = "Name must be at most 10 characters")]
public string Name { get; set; }

Phone number attribute

The PhoneAttribute class is used to specify that a property value must match a specified phone number pattern. The DataForm component displays an error message if the property value does not match the specified phone number pattern.

[Phone(ErrorMessage = "Phone number is not valid")]
public string PhoneNumber { get; set; }

Email address attribute

The EmailAddressAttribute class is used to specify that a property value must match a specified email address pattern. The DataForm component displays an error message if the property value does not match the specified email address pattern.

[EmailAddress(ErrorMessage = "Email address is not valid")]
public string Email { get; set; }

URL attribute

The UrlAttribute class is used to specify that a property value must match a specified URL pattern. The DataForm component displays an error message if the property value does not match the specified URL pattern.

[Url(ErrorMessage = "URL is not valid")]
public string Url { get; set; }

Enum data type attribute

The EnumDataTypeAttribute class is used to specify that a property value must be a member of the specified enumeration. The DataForm component displays an error message if the property value is not a member of the specified enumeration.

[EnumDataType(typeof(Gender), ErrorMessage = "Please enter a valid gender")]
 public string Gender { get; set; }

Compare attribute

The CompareAttribute class is used to specify that a property value must match the value of another property in the same class. The DataForm component displays an error message if the property value does not match the value of the other property.

[Compare("Password", ErrorMessage = "Passwords do not match")]
public string ConfirmPassword { get; set; }

String length attribute

The StringLengthAttribute class is used to specify the minimum and maximum length constraints for the value of a property. The DataForm component displays an error message if the property value is not within the specified length constraints.Additionally editor component will not allow to enter more than the specified length.

[StringLength(100, MinimumLength = 3, ErrorMessage = "Name must be between 5 and 10 characters")]
public string Name { get; set; }

Data type attribute

The DataTypeAttribute class is used to specify the data type of a property. The DataForm component uses this attribute to determine the editor type for the property.The below table explains the supported data types and the corresponding editor types.

Data type Editor type Image
DataType.Date SfDatePicker Blazor DataForm DataType.Date
DataType.Time SfTimePicker Blazor DataForm DataType.Time
DataType.DateTime SfDateTimePicker Blazor DataForm DataType.DateTime
DataType.Currency SfNumericTextBox Blazor DataForm DataType.Currency
DataType.PhoneNumber SfMaskedTextBox Blazor DataForm DataType.PhoneNumber
DataType.CreditCard SfMaskedTextBox Blazor DataForm DataType.CreditCard
DataType.MultilineText SfTextBox Blazor DataForm DataType.MultilineText
DataType.Password SfTextBox Blazor DataForm DataType.Password
<ul><li>DataType.EmailAddress</li><li>DataType.Url</li><li>DataType.Text</li><li> DataType.ImageUrl</li><li> DataType.Html</li></ul> SfTextBox Blazor DataForm DataType.EmailAddress

If any other data type is specified other than the above table, the DataForm component uses the SfTextBox editor by default.

[DataType(DataType.Date)]
public DateTime? DateOfBirth { get; set; }

Editable attribute

The EditableAttribute class is used to specify that a property can be edited in the DataForm component.

[Editable(false)]
public string ID { get; set; }

Bindable attribute

The BindableAttribute class is used to specify whether the property should be automatically generated as a field in the DataForm component similar to the AutoGenerateField property in the Display attribute. If set to false the property will not be generated as a field in the DataForm component.

[Bindable(false)]
public string ID { get; set; }

Read only attribute

The ReadOnlyAttribute class is used to specify whether the property should be read-only in the DataForm component.

[ReadOnly(true)]
public string ID { get; set; }

Custom attributes

Data form display options attribute

The DataFormDisplayOptionsAttribute attribute is used to specify the display options for a property in the DataForm component. The DataForm component uses this attribute to determine the ColumnSpanfor the property.

<SfDataForm ID="MyForm"
            EditContext="@UserEditContext"
            ColumnCount=6
            ColumnSpacing="10px"
            Width="70%"
            ButtonsAlignment="FormButtonsAlignment.Right">
    <FormValidator>
        <DataAnnotationsValidator></DataAnnotationsValidator>
    </FormValidator>
    <FormItems>
        <FormAutoGenerateItems></FormAutoGenerateItems>
    </FormItems>
    <FormButtons>
        <SfButton>Pay $@PaymentDetails.PaymentAmount </SfButton>
    </FormButtons>
</SfDataForm>

@code {
    EditContext UserEditContext { get; set; }
    public char PromptCharacter = ' ';
    protected override Task OnInitializedAsync()
    {
        UserEditContext = new EditContext(PaymentDetails);
        return base.OnInitializedAsync();
    }
    private PaymentDetailsModel PaymentDetails = new PaymentDetailsModel();
}
public class ZipCodes
 {
     public int? Code { get; set; }
     public string City { get; set; }
 }
 
 private List<ZipCodes> ZipData = new List<ZipCodes>()
 {
     new ZipCodes(){ Code=90210 , City="Beverly Hills, 90210 (California)"  },
     new ZipCodes(){ Code=94558, City="Napa Valley, 94558 (California)"  },
     new ZipCodes(){ Code=33139, City="South Beach, 33139 (Florida)"  },
     new ZipCodes(){ Code=10019, City="Manhattan, 10019 (New York)"  },
     new ZipCodes(){ Code=94043, City="Silicon Valley, 94043 (California)"  },
  };

 public class PaymentDetailsModel
 {
     [Required(ErrorMessage = "Please enter your payment amount.")]
     [Display(Name = "Payable Amount", Prompt = "Currency format")]
     [Range(1, 10000000)]
     [DataFormDisplayOptions(ColumnSpan = 6)]
     public double PaymentAmount { get; set; }

     [Required(ErrorMessage = "Please enter your name.")]
     [Display(Name = "Name on card", Prompt = "Enter the name on the card")]
     [DataFormDisplayOptions(ColumnSpan = 6)]
     public string NameOnCard { get; set; }

     [Required(ErrorMessage = "Please enter your card number.")]
     [Display(Name = "Card Number", Prompt = "Enter the card number")]
     [DataFormDisplayOptions(ColumnSpan = 6)]
     public string CardNumber { get; set; }

     [Required(ErrorMessage = "Please enter card expiry date.")]
     [Display(Name = "Expiry Date", Prompt = "MM/YY")]
     [DataFormDisplayOptions(ColumnSpan = 2)]
     public DateTime? ExpiryDate { get; set; }

     [Required(ErrorMessage = "Please enter security code.")]
     [Display(Name = "Security Code", Prompt = "e.g. 123")]
     [DataFormDisplayOptions(ColumnSpan = 2)]
     public string SecurityCode { get; set; }

     [Required(ErrorMessage = "Please enter your zip code.")]
     [Display(Name = "Zip code", Prompt = "Enter Zip code")]
     [DataFormDisplayOptions(ColumnSpan = 2)]
     public int? ZipCode { get; set; }

     [Required(ErrorMessage = "Please enter your shipping address.")]
     [Display(Name = "Shipping Address", Prompt = "Flat number , Apartment ,Suite etc.")]
     [DataFormDisplayOptions(ColumnSpan = 3)]
     [DataType(DataType.MultilineText)]
     public string ShippingAddress { get; set; }

     [Display(Name = "Billing Address", Prompt = "The billing address.")]
     [DataFormDisplayOptions(ColumnSpan = 3)]
     [DataType(DataType.MultilineText)]
     public string BillingAddress { get; set; }

     [Required(ErrorMessage = "Please agree with the terms.")]
     [Display(Name = "Accept terms and conditions", Prompt = "Please agree with the terms.")]
     [DataFormDisplayOptions(ColumnSpan = 6)]
     [Range(typeof(bool), "true", "true", ErrorMessage = "Please agree with the terms.")]
     public bool AcceptTerms { get; set; }
 }

Blazor DataForm Custom Attributes

Custom validation

A custom validation attribute in .NET is a class that inherits from the ValidationAttribute abstract class and overrides the IsValid method. This method is called when the attribute is applied to a property and the property’s value is being validated.

In the IsValid method, you can define your custom validation logic. If the validation fails, you return a ValidationResult object with an error message. If the validation passes, you return ValidationResult.Success.

@using System;
@using System.ComponentModel.DataAnnotations;
@using Syncfusion.Blazor.DataForm;
@using System.Text.RegularExpressions;

<SfDataForm ID="MyForm"
            Model="@EmployeeModel"
            Width="50%">
    <FormValidator>
        <DataAnnotationsValidator></DataAnnotationsValidator>
    </FormValidator>
    <FormItems>
        <FormGroup LabelText="Sign Up Details">
            <FormItem Field="@nameof(EmployeeModel.Name)" LabelText="Name"></FormItem>
            <FormItem Field="@nameof(EmployeeModel.Email)" LabelText="Email Id"></FormItem>
            <FormItem Field="@nameof(EmployeeModel.Password)" LabelText="Password" EditorType="FormEditorType.Password"> </FormItem>
            <FormItem Field="@nameof(EmployeeModel.ConfirmPassword)" LabelText="Confirm Password" EditorType="FormEditorType.Password"> </FormItem>
        </FormGroup>
    </FormItems>
</SfDataForm>


@code {
    private EmployeeDetails EmployeeModel = new EmployeeDetails();

    public class EmployeeDetails
    {
        [Required]
        public string? Name { get; set; }

        [Required]
        [PasswordValidation(ErrorMessage = "This field should not be Empty")]
        public string? Password { get; set; }

        [Required]
        [Compare("Password", ErrorMessage = "Confirm Password must match Password")]
        public string? ConfirmPassword { get; set; }

        [Required]
        [EmailValidation(ErrorMessage = "This field should not be Empty")]
        public string? Email { get; set; }
    }

    public class PasswordValidationAttribute : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            string fieldValue = value as string;

            if (fieldValue.Length < 10)
            {
                return new ValidationResult("Password should have at least 10 characters", new[] { validationContext.MemberName });
            }

            if (!Regex.IsMatch(fieldValue, @"[A-Z]"))
            {
                return new ValidationResult("Password should contain at least one uppercase letter", new[] { validationContext.MemberName });
            }

            if (!Regex.IsMatch(fieldValue, @"[a-z]"))
            {
                return new ValidationResult("Password should contain at least one lowercase letter", new[] { validationContext.MemberName });
            }

            if (!Regex.IsMatch(fieldValue, @"[@#$%^&+=]"))
            {
                return new ValidationResult("Password should contain at least one special character", new[] { validationContext.MemberName });
            }

            return ValidationResult.Success;
        }
    }

    public class EmailValidationAttribute : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            string email = value as string;

            if (!IsValidEmail(email))
            {
                return new ValidationResult("Email address is not valid..", new[] { validationContext.MemberName });
            }

            return ValidationResult.Success;
        }

        private bool IsValidEmail(string email)
        {
            return Regex.IsMatch(email, @"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$");
        }
    }
}

In the above example, In the PasswordValidationAttribute class, the IsValid method checks if the password meets certain criteria (length, contains uppercase letter, contains lowercase letter, contains special character). If it doesn’t, it returns a ValidationResult with an appropriate error message.In the EmailValidationAttribute class, the IsValid method checks if the email is in a valid format. If it’s not, it returns a ValidationResult with an error message.

Blazor DataForm Custom Validation