1

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>
5
  • Inside the addMethod method check exactly what you have done in your ValidateJsonAttribute and return true or false based on the checking. Commented Jan 25, 2019 at 7:58
  • 1
    In this case remote remote attribute validation would be much easier. Commented Jan 25, 2019 at 7:59
  • @TanvirArjel thanks for the response and I will let you know :-) Commented Jan 25, 2019 at 8:01
  • 1
    @TanvirArjel it works and it is quite easy, thanks. If you put it as solution I would be happy to accept it. Commented Jan 25, 2019 at 15:17
  • Okay!Thank you. I am writing! Commented Jan 25, 2019 at 15:21

1 Answer 1

1

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);
    }

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.