user2402624
user2402624

Reputation: 231

MVC custom validation attribute

Is it possible to get HTML custom attribute (client-side) when server fire the ValidationResult.

I am doing like this

Model Class :

    public class Model_Test
{
    [Age(18,50)]
    [Display(Name = "My Age")]
    public int Age { get; set; }
}

HTML :

@model CustomValidation.Models.Model_Test
@using (@Html.BeginForm("Index","Test"))
{
    @Html.TextBoxFor(m => m.Age, new { @myValidate="Yes" })
    @Html.TextBoxFor(m => m.Age, new { @myValidate="No" })
    <input type="submit" />
}

Custom Attribute Class :

    public class AgeAttribute : ValidationAttribute
    {
        private readonly int _MinAge = 0;
        private readonly int _MaxAge = 0;
        private const string errorMsg = "{0} must at least {1} or not more than {2}";

        public AgeAttribute(int MinAge, int MaxAge)
            : base(() => errorMsg)
        {
            _MinAge = MinAge;
            _MaxAge = MaxAge;
        }

        //Server-Side Validation
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {



        **// Can we get the HTML Attribute from client side and implement some condition at here???
        // etc...
        // if (html.attribute("myValidate") == "Yes") {
        //    *condition......*
        // } else {
        //    *condition......***
        // }



            if (value != null)
            {
                int data = (int)value;
                if (!(data > (int)_MinAge && data < (int)_MaxAge))
                {
                    return new ValidationResult(null);
                }
            }
            return ValidationResult.Success;
        }
    }

In my code , I got 2 textboxes and each of them with custom attribute "myValidate="Yes/No" .
Can I bring this attribute to server-side ValidationResult for my validation purpose? If not, Is there any other proper way to do this?

Upvotes: 0

Views: 3605

Answers (1)

Stokedout
Stokedout

Reputation: 11055

You are on the right tracks but the best way to have one field with validation and another without is just use two separate properties and only annotate one with the custom attribute:

public class Model_Test
{
    [Age(18,50)]
    [Display(Name = "My Age")]
    public int Age { get; set; }

    [Display(Name = "Another age")]
    public int AnotherAge { get; set; }
}

Then within your controller you can do what you like with the property and avoid the need to make your validation code more complex.

Upvotes: 2

Related Questions