Search code examples
asp.net-coredata-annotationsunobtrusive-validation

ASP.NET Core Create a Custom Data Annotation for JSON validation also from client side


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>

Solution

  • To reduce the complexity you can simply use RemoteAttribute for providing unobtrusive ajax validation as follows:

    In your model class property:

    public class MyModel
    {
        [Remote("IsInputStringValidJson", "Validation", ErrorMessage = "Input string is not a valid Json string")]
        public string MyProperty { get; set; }
    }
    

    Then in the Validation controller:

    public class ValidationController : Controller
    {
    
        public JsonResult IsInputStringValidJson(string myProperty)
        { 
            try
            {
                 var result = JsonConvert.DeserializeObject(myProperty);
            }
            catch (JsonReaderException ex)
            {
                 return Json(false)
            }
    
            return Json(true);
        }
    
    }