Skip to content

Add checkbox checked validation #58044

@vsfeedback

Description

@vsfeedback

This issue has been moved from a ticket on Developer Community.


Hi, this is basic functionality as every (or most of) register forms has a "agree to terms&conditions" checkbox. So, form is valid only when this checkbox is checked. I was very suprised when I found that [Require] attribute on model is not the way it should be, and that is no built in solution for that. So, I think you should implement this function.

My example:

Attribute class:

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class CheckBoxCheckedAttribute : ValidationAttribute, IClientModelValidator
{
	public void AddValidation(ClientModelValidationContext context)
	{
		if (context == null)
		{
			throw new ArgumentNullException(nameof(context));
		}

MergeAttribute(context. Attributes, "data-val", "true");
		MergeAttribute(context. Attributes, "data-val-chboxreq", GetErrorMessage(context. ModelMetadata));
	}

public override bool IsValid(object value)
	{
		return (value is bool && (bool)value);
	}

private static void MergeAttribute(IDictionary<string, string> attributes, string key, string value)
	{
		if (!attributes. ContainsKey(key))
		{
			attributes. Add(key, value);
		}
	}

private string GetErrorMessage(ModelMetadata modelMetadata)
	{
		if (modelMetadata == null)
		{
			throw new ArgumentNullException(nameof(modelMetadata));
		}

return ErrorMessageString;
	}
}

Usage on model (other field removed for brevity):

public class RegisterUserModel
{
	[CheckBoxChecked(ErrorMessageResourceName = nameof(LangRes.AcceptTerms_Error), ErrorMessageResourceType = typeof(LangRes))]
	public bool TermsAndConditions { get; set; }
}

Usage in view:

<div class="form-group">
    <div class="form-check">
        <input type="checkbox" class="form-check-input" asp-for="TermsAndConditions" id="terms" />
        <label class="form-check-label" asp-for="TermsAndConditions">I accept</label>
    </div>
    <span asp-validation-for="TermsAndConditions" class="text-danger"></span>
</div>

And some JavaScript to add in unobtrusive validation:

$.validator.addMethod("chboxreq", function (value, element, param) {
    if (element.type != "checkbox")
        return false;

return element.checked;
});

$.validator.unobtrusive.adapters.addBool("chboxreq");

Please, be so kind and add this :)


Original Comments

Feedback Bot on 2/18/2021, 11:09 PM:

Thank you for taking the time to provide your suggestion. We will do some preliminary checks to make sure we can proceed further. We’ll provide an update once the issue has been triaged by the product team.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Author: Migration Bot 🤖The issue was created by a issue mover bot. The author may not be the actual author.area-mvcIncludes: MVC, Actions and Controllers, Localization, CORS, most templates

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions