Drop down list validation message mvc

asp.net-mvc-3drop-down-menurazorvalidation

In my viewModel I have

public string Addressline1 { get; set; }
public List<SelectListItem> StateList
    {
        get
        {
            return State.GetAllStates().Select(state => new SelectListItem { Selected = false, Text = state.Value, Value = state.Value }).ToList();
        }
    }

In the view I have

@Html.DropDownListFor(model => model.StateCode, Model.StateList, "select")

when AddressLine1 is entered, then the statelist DropDownList selection is Required.How do I validate and show an error message when no state is selected in the Drop down list other than default "select" value?

Best Answer

Decorate your StateCode property with the [Required] attribute:

[Required(ErrorMessage = "Please select a state")]
public string StateCode { get; set; }

public IEnumerable<SelectListItem> StateList
{
    get
    {
        return State
            .GetAllStates()
            .Select(state => new SelectListItem 
            { 
                Text = state.Value, 
                Value = state.Value 
            })
            .ToList();
    }
}

and then you could add a corresponding validation error message:

@Html.DropDownListFor(model => model.StateCode, Model.StateList, "select")
@Html.ValidationMessageFor(model => model.StateCode)

UPDATE:

Alright it seems that you want to conditionally validate this StateCode property depending on some other property on your view model. Now that's an entirely different story and you should have explained this in your original question. Anyway, one possibility is to write a custom validation attribute:

public class RequiredIfPropertyNotEmptyAttribute : ValidationAttribute
{
    public string OtherProperty { get; private set; }
    public RequiredIfPropertyNotEmptyAttribute(string otherProperty)
    {
        if (otherProperty == null)
        {
            throw new ArgumentNullException("otherProperty");
        }
        OtherProperty = otherProperty;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var property = validationContext.ObjectType.GetProperty(OtherProperty);
        if (property == null)
        {
            return new ValidationResult(string.Format(CultureInfo.CurrentCulture, "{0} is an unknown property", new object[]
            {
                OtherProperty
            }));
        }
        var otherPropertyValue = property.GetValue(validationContext.ObjectInstance, null) as string;
        if (string.IsNullOrEmpty(otherPropertyValue))
        {
            return null;
        }

        if (string.IsNullOrEmpty(value as string))
        {
            return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
        }

        return null;
    }
}

and now decorate your StateCode property with this attribute, like so:

public string AddressLine1 { get; set; }

[RequiredIfPropertyNotEmpty("AddressLine1", ErrorMessage = "Please select a state")]
public string StateCode { get; set; }

Now assuming you have the following form:

@using (Html.BeginForm())
{
    <div>
        @Html.LabelFor(x => x.AddressLine1)
        @Html.EditorFor(x => x.AddressLine1)
    </div>

    <div>
        @Html.LabelFor(x => x.StateCode)
        @Html.DropDownListFor(x => x.StateCode, Model.States, "-- state --")
        @Html.ValidationMessageFor(x => x.StateCode)
    </div>

    <input type="submit" value="OK" />
}

the StateCode dropdown will be required only if the user entered a value into the AddressLine1 field.

Related Topic