Quantcast
Channel: All About ASP.NET and ASP.NET Core 2 Hosting BLOG
Viewing all articles
Browse latest Browse all 427

ASP.NET MVC Hosting - ASPHostPortal.com :: Conditional Validation Utilize ValidationAttribute

$
0
0

In ASP.NET MVC we can validate each input field by decorating the corresponding property in the model class with some validation attributes like Required, MaxLength, MinLength, etc.

Sometime we need to validate a property according to another property value for example if we have a registration form and we need the user enter his age if he is a male and age not required if the user sex is female. So if we decorated the Age property with Required attribute it will show error message even if the user is female, so we need to bypass this check with females.

Assume our registration form will contains three fields, name, sex and age, and its model will be as follows

public class RegisterationModel
{
    [Required(ErrorMessage = "*")]
    public String Name { get; set; }

    [Required(ErrorMessage = "*")]
    [Display(Name = "Gender")]
    public Sex Sex { get; set; }

    [RequiredIf("Sex", Sex.Male, "enter your age")]
    public Int32? Age { get; set; }
}
public enum Sex
{
    Female = 1,
    Male = 2
}

Note we decorated the Age property with RequiredIf attribute, that we will create and it inherits ValidationAttribute class and override IsValid method.

The RequiredIf attribute accepts three pramaters in its constructor, first parameter is the name of the property will affect the validation (Sex property), second parameter is the value of that property that make the Age is required(Male), and third parameter is the error message that will be displayed if the validation failed.

public class RequiredIfAttribute : ValidationAttribute
{
    private String PropertyName { get; set; }
    private String ErrorMessage { get; set; }
    private Object DesiredValue { get; set; }

    public RequiredIfAttribute(String propertyName, Object desiredvalue, String errormessage)
    {
        this.PropertyName = propertyName;
        this.DesiredValue = desiredvalue;
        this.ErrorMessage = errormessage;
    }

    protected override ValidationResult IsValid(object value, ValidationContext context)
    {
        Object instance = context.ObjectInstance;
        Type type = instance.GetType();
        Object proprtyvalue = type.GetProperty(PropertyName).GetValue(instance, null);
        if (proprtyvalue.ToString() == DesiredValue.ToString() && value == null)
        {
            return new ValidationResult(ErrorMessage);
        }
        return ValidationResult.Success;
    }
}

In the IsValid method we get the current instance of RegisterationModel class using ValidationContext object and get the value of the Sex property then compare it with the desire value(Male) which make the Age is required. If the current value of Sex property equal the desired value then IsValid will return new ValidationResult object with the supplied error message.

Unfortunately this technique is working in server side only.


Recommended ASP.NET MVC 6 Hosting


ASPHostPortal.com
ASPHostPortal.com
is the leading provider of Windows hosting and affordable ASP.NET MVC Hosting. ASPHostPortal proudly working to help grow the backbone of the Internet, the millions of individuals, families, micro-businesses, small business, and fledgling online businesses. ASPHostPortal has ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2015, .NET 5/ASP.NET 4.5.2, ASP.NET MVC 6.0/5.2, Silverlight 6 and Visual Studio Lightswitch, ASPHostPortal guarantees the highest quality product, top security, and unshakeable reliability, carefully chose high-quality servers, networking, and infrastructure equipment to ensure the utmost reliability.



Viewing all articles
Browse latest Browse all 427

Trending Articles