Make the email field required based on the dropdow

2019-08-20 23:15发布

问题:

My application is in mvc 3

I have a ddlfor in my view which lists two values A and B. There is one more field email in same view I need to make this email field a required or mandatory filed only if the selected value of the ddl is 'A'.And no need to validate if the value selected is 'B'. How can i implement this scenario.PLsss help me

Now in my model, email is a mandatory field. Do i need to change that? If i change that where i will make email mandatory and not mandatory based on ddl value?

Pls advice me. Thanks in advance, Priya

回答1:

You can do that in JQuery. In Jquery check the value of drop down if 'A' and email field is empty return false so that form will not be submitted.

On server side rather than using data annotation you can have a custom method to validate.



回答2:

IValidatableObject interface allows you to perform validation at model level :

public class MyModel : IValidatableObject
{
    public string Email { get; set; }
    public string SelectedValue { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (SelectedValue == "A" && string.IsNullOrEmpty(Email))
        {
            yield return new ValidationResult("Email address is required.", new [] { "Email" });
        }
    }
}

It will highlight Email field if your selected value in the dropdownlist is "A".