1

I am developing an ASP.Net MVC 5 Web application and I am having some difficulties with making custom validation on Checkbox list. Validation I need that at least one checkbox must be checked

My ViewModel

public class EditUtilisateurViewModel
{
public long Id { get; set; }

[Required(AllowEmptyStrings = false, ErrorMessage = " Required ")]
[Display(Name = "Login")]
public string UserName { get; set; }

[Required(AllowEmptyStrings = false, ErrorMessage = "Required")]
[Display(Name = "Email")]
[EmailAddress (ErrorMessage = "Invalid Email")]
public string Email { get; set; }

[CheckOneSelected(ErrorMessage = "Please select role")]
public IEnumerable<System.Web.Mvc.SelectListItem> RolesList { get; set; }

}

My Controller

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "Id,UserName,Email")] EditUtilisateurViewModel editUser, params string[] selectedRole)
{
if (ModelState.IsValid)
{
    // ToDo ...

    return RedirectToAction("Index");
}
}

My View

@model MyProject.Areas.Admin.Models.EditUtilisateurViewModel

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    @Html.HiddenFor(m => m.Id)
    <table
        <tbody>
            < >
                <th>
                    @Html.LabelFor(m => m.UserName)
                </th>
                <td>
                    @Html.TextBoxFor(m => m.UserName)
                    @Html.ValidationMessageFor(m => m.UserName)
                </td>
            </tr>
            <tr>
                <th>
                    @Html.LabelFor(m => m.Email)
                </th>
                <td>
                    @Html.TextBoxFor(m => m.Email, new { @class = "form-control", @disabled = "disabled" })
                    @*@Html.ValidationMessageFor(m => m.Email)*@
                </td>
            </tr>
            <tr>
                <th>@Html.Label("Roles")</th>
                <td>
                    <span>
                        @foreach (var item in Model.RolesList)
                        {
                            @*<input type="checkbox" id="@item.Value" name="SelectedRole" value="@item.Value" checked="@item.Selected" class="checkbox-inline" />*@
                            @Html.CheckBoxFor(m => item.Selected, new { id = item.Value, @Value = item.Value, @Name = "selectedRole[]", @class = "checkbox-inline", data_val = "true", data_val_verifListe = " Select field " })
                            @Html.Label(item.Value, new { @class = "checkbox-inline-label" })
                        }
                    </span>
                    @Html.ValidationMessageFor(m => m.RolesList)
                </td>
            </tr>
        </tbody>
    </table>
    <p>
        <input type="submit" value="Update" />
    </p>
}

I tried Validation like below but and have essues

namespace ...
{
    public class CheckOneSelectedAttribute : ValidationAttribute, IClientValidatable
    {
        public string[] SelectedRole { get; private set; }

        public CheckOneSelectedAttribute(string SelectedValue) : base("Select field")
        {
            if (SelectedValue != null && SelectedValue.Length > 0)
                SelectedRole = SelectedValue;
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value != null)
            {
                if (selectedRole != null)
                {
                    if (selectedRole.Length == 0)
                    {
                        return new ValidationResult("Select field ");
                    }
                }
            }
            else
            {
                return new ValidationResult("Null parameter");
            }
            return ValidationResult.Success;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            yield return new ModelClientValidationRule()
            {
                ErrorMessage = ErrorMessageString,
                ValidationType = "CheckOneSelected"
            };
        }
    }
}

Can some one please help me? Thanks.

2
  • 1
    That is a lot of code. What kind of issue are you having with it? Commented Jan 8, 2015 at 17:47
  • Always return Null Value of parameter. Commented Jan 8, 2015 at 17:58

1 Answer 1

1

In the controller part which is post and takes []list , You should check the length of the list by that u can make a validation for that .

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.