I managed to create a custom Data-Annotation to validate whether the value is a valid JSON. The class of course can be improved but my issue is how to link the clint-side validation to the class:
public sealed class ValidateJsonAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object json, ValidationContext validationContext)
{
try
{
var result = JsonConvert.DeserializeObject(json.ToString());
}
catch (JsonReaderException ex)
{
return new ValidationResult(ex.Message);
}
return ValidationResult.Success;
}
}
This is an example of a client side validation, how can I fix it to fit to my need?
<script type="text/javascript">
$.validator.addMethod("cannotbevalue", function (value, element, params) {
if ($(element).val() == params.targetvalue) {
return false;
}
return true;
});
$.validator.unobtrusive.adapters.add('cannotbevalue', ['value'], function (options) {
options.rules['cannotbevalue'] = { targetvalue: options.params.value };
options.messages['cannotbevalue'] = options.message;
});
</script>
addMethodmethod check exactly what you have done in yourValidateJsonAttributeand return true or false based on the checking.