Custom validation does not work on client side

I am writing a custom attribute to require a property in the viewmodel if another property has the specified value.

I used this post for reference: RequiredIf Conditional Validation Attribute

But there were problems with .NET Core versions for IClientModelValidator. In particular, server-side validation works as expected with ModelState.IsValid returns false and ModelState errors containing my custom error codes. I feel that I am missing something when translating between different versions of the validator.

The old (working) solution has the following:

public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata,
    ControllerContext context)
{
    var rule = new ModelClientValidationRule
    {
        ErrorMessage = ErrorMessageString,
        ValidationType = "requiredif",
    };
    rule.ValidationParameters["dependentproperty"] =
        (context as ViewContext).ViewData.TemplateInfo.GetFullHtmlFieldId(PropertyName);
    rule.ValidationParameters["desiredvalue"] = DesiredValue is bool
        ? DesiredValue.ToString().ToLower()
        : DesiredValue;

    yield return rule;
}

Based on the changes to IClientModelValidator outlined here: https://github.com/aspnet/Announcements/issues/179 I wrote the following methods:

    public void AddValidation(ClientModelValidationContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }
        MergeAttribute(context.Attributes, "data-val", "true");

        var errorMessage = FormatErrorMessage(context.ModelMetadata.GetDisplayName());
        MergeAttribute(context.Attributes, "data-val-requiredif", errorMessage);

        MergeAttribute(context.Attributes, "data-val-requiredif-dependentproperty", PropertyName);

        var desiredValue = DesiredValue.ToString().ToLower();
        MergeAttribute(context.Attributes, "data-val-requiredif-desiredvalue", desiredValue);
    }

    private bool MergeAttribute(
        IDictionary<string, string> attributes,
        string key,
        string value)
    {
        if (attributes.ContainsKey(key))
        {
            return false;
        }
        attributes.Add(key, value);
        return true;
    }

, , JS . , - .

    $.validator.addMethod("requiredif", function (value, element, parameters) {
        var desiredvalue = parameters.desiredvalue;
        desiredvalue = (desiredvalue == null ? "" : desiredvalue).toString();
        var controlType = $("input[id$='" + parameters.dependentproperty + "']").attr("type");
        var actualvalue = {}
        if (controlType === "checkbox" || controlType === "radio") {
            var control = $("input[id$='" + parameters.dependentproperty + "']:checked");
            actualvalue = control.val();
        } else {
            actualvalue = $("#" + parameters.dependentproperty).val();
        }
        if ($.trim(desiredvalue).toLowerCase() === $.trim(actualvalue).toLocaleLowerCase()) {
            var isValid = $.validator.methods.required.call(this, value, element, parameters);
            return isValid;
        }
        return true;
    });
    $.validator.unobtrusive.adapters.add("requiredif", ["dependentproperty", "desiredvalue"], function (options) {
        options.rules["requiredif"] = options.params;
        options.messages["requiredif"] = options.message;
    });

?

EDIT: , , , , HTML :

<input class="form-control" type="text" data-val="true" data-val-requiredif="Profession Other Specification is Required" data-val-requiredif-dependentproperty="ProfessionTypeId" data-val-requiredif-desiredvalue="10" id="ProfessionOther" name="ProfessionOther" value="" placeholder="Please Specify Other">
+4
1

, , . , , , , , , jquery.validate.js - . , . , , ( ).

, validator , . JS jQuery ready, script ( , jQuery). , - !

TypeScript, , JavaScript .

"MaybeRequired" Typescript class:

export class RequiredSometimesValidator {
    constructor() {
        // validator code starts here
        $.validator.addMethod("requiredsometimes", function (value, element, params) {
            var $prop = $("#" + params);
            // $prop not found; search for a control whose Id ends with "_params" (child view)
            if ($prop.length === 0) 
                $prop = $("[id$='_" + params + "']");

            if ($prop.length > 0) {
                var ctrlState = $prop.val();
                if (ctrlState === "EditableRequired" && (value === "" || value === "Undefined"))
                    return false;
            }
            return true;
        });

        $.validator.unobtrusive.adapters.add("requiredsometimes", ["controlstate"], function (options) {
            options.rules["requiredsometimes"] = options.params["controlstate"];
            options.messages["requiredsometimes"] = options.message;
        });
        // validator code stops here
    }
}

boot-client.ts( , JavaScript), ( , ) document.ready:

export class Blueprint implements IBlueprint {
    constructor() {
        // this occurs prior to document.ready
        this.initCustomValidation();

        $(() => { 
            // document ready stuff here
        });
    }
    private initCustomValidation = (): void => {
        // structure allows for load of additional client-side validators
        new RequiredSometimesValidator();
    }
}

, TypeScript, :

<script>
    $.validator.addMethod("requiredsometimes", function (value, element, params) {
        var $prop = $("#" + params);
        // $prop not found; search for a control whose Id ends with "_params" (child view)
        if ($prop.length === 0) 
            $prop = $("[id$='_" + params + "']");

        if ($prop.length > 0) {
            var ctrlState = $prop.val();
            if (ctrlState === "EditableRequired" && (value === "" || value === "Undefined"))
                return false;
        }
        return true;
    });

    $.validator.unobtrusive.adapters.add("requiredsometimes", ["controlstate"], function (options) {
        options.rules["requiredsometimes"] = options.params["controlstate"];
        options.messages["requiredsometimes"] = options.message;
    });

    $(function() {
        // document ready stuff
    });

</script>
+1

Source: https://habr.com/ru/post/1664602/


All Articles