问题
I am having trouble getting client side validation to work in ASP.NET Core MVC. I've googled and applied the example from here (http://www.discuzfeed.com/code/lotooslo-mvc-6-client-side-validation-for-custom-attribute.html) but no luck.
Here is my code
Attribute
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public sealed class CannotBeRedAttribute : ValidationAttribute, IClientModelValidator
{
public override bool IsValid(object value)
{
var message = value as string;
return false;
//return message?.ToLower() == "red";
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
ClientModelValidationContext context)
{
yield return new ModelClientValidationRule(
"cannotbered",
FormatErrorMessage(ErrorMessage));
}
}
View Model
[CannotBeRed(ErrorMessage = "Not red!")]
public string SelectedCompanyIds { get; set; }
View
<input type="hidden" name="test" class="form-control" id="selectCompanyIdControl" data-bind="value: SelectedReportCompanyIds" asp- for="SelectedCompanyIds" />
@<script type="text/javascript">
require(['jquery', 'knockout-es5', 'jquery-validation', 'jquery-validation-unobtrusive', 'pubsubjs', 'ReportEditViewModel'], function(jquery, knockout, jQueryVal, jQueryValUnobtrusive, pubsub, vm) {
jquery(document).ready(function () {
jquery.validator.addMethod("cannotbered",
function (value, element, parameters) {
alert("READ");
return value.toLowerCase() !== "red";
});
jquery.validator.unobtrusive.adapters.add('cannotbered', [], function (options) {
alert("ADAPATER");
options.rules.cannotbered = {};
options.messages['cannotbered'] = options.message;
});
Ignore fact that brackets not closed correctly in view, there are other JS parts to do with knockout which not copying here as not relevant.
The GetClientValidationRules
method is being hit, but the alerts in the JS are not. Just for info, when run developer tools in chrome or IE I can see that the jquery validation and unobtrusive libraries are loaded, and that there are no console errors. The validation tag seems to be ok on the input box....
<input type="hidden" name="test" class="form-control" id="selectCompanyIdControl" data-bind="value: SelectedReportCompanyIds" data-val="true" data-val-cannotbered="Not red!" value="" />
So I think I'm just missing one step, but cant think what it could be. Any pointers?
来源:https://stackoverflow.com/questions/37676377/client-side-validation-in-asp-net-core-mvc