Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create regularExpressionAttribute with dynamic pattern come from model property

public class City
{
   [DynamicReqularExpressionAttribute(PatternProperty = "RegEx")]
   public string Zip {get; set;}
   public string RegEx { get; set;} 
}

I woud like to create this attribute where the pattern come from an other property and not declare static like in the original RegularExpressionAttribute.

Any ideas would be appreciated - Thanks

like image 908
Philipp Troxler Avatar asked May 26 '11 11:05

Philipp Troxler


1 Answers

Something among the lines should fit the bill:

public class DynamicRegularExpressionAttribute : ValidationAttribute
{
    public string PatternProperty { get; set; }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        PropertyInfo property = validationContext.ObjectType.GetProperty(PatternProperty);
        if (property == null)
        {
            return new ValidationResult(string.Format("{0} is unknown property", PatternProperty));
        }
        var pattern = property.GetValue(validationContext.ObjectInstance, null) as string;
        if (string.IsNullOrEmpty(pattern))
        {
            return new ValidationResult(string.Format("{0} must be a valid string regex", PatternProperty));
        }

        var str = value as string;
        if (string.IsNullOrEmpty(str))
        {
            // We consider that an empty string is valid for this property
            // Decorate with [Required] if this is not the case
            return null;
        }

        var match = Regex.Match(str, pattern);
        if (!match.Success)
        {
            return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
        }

        return null;
    }
}

and then:

Model:

public class City
{
    [DynamicRegularExpression(PatternProperty = "RegEx")]
    public string Zip { get; set; }
    public string RegEx { get; set; }
}

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var city = new City
        {
            RegEx = "[0-9]{5}"
        };
        return View(city);
    }

    [HttpPost]
    public ActionResult Index(City city)
    {
        return View(city);
    }
}

View:

@model City
@using (Html.BeginForm())
{
    @Html.HiddenFor(x => x.RegEx)

    @Html.LabelFor(x => x.Zip)
    @Html.EditorFor(x => x.Zip)
    @Html.ValidationMessageFor(x => x.Zip)

    <input type="submit" value="OK" />
}
like image 118
Darin Dimitrov Avatar answered Oct 12 '22 00:10

Darin Dimitrov