0

I have a complex validation on a field that depends on other 3 fieldsthe validation on the server is simple because the method I use "Validate"

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
   // my validation
   if(complex_condition)
   {
       yield return new
               ValidationResult("my error", new List<string> {"field1"});
   }
}

But do not know how to do the same on the client. Could put the validation in the event "submit", but I would like the show as an error message in the field that I am validating, as if fired the required field validation.

Thank you.

Edit: Solution after the response @DarinDimitrov:

Javascript:

$.validator.addMethod('mycustomvalidation', function (value, element, parameters) {

    if (value.length < 6) {
        return false;
    }

    return true;
});

$.validator.unobtrusive.adapters.add('mycustomvalidation', [], function (options) {
    options.rules['mycustomvalidation'] = {};

    for(var key in options.params) {
        options.rules['mycustomvalidation'][key] =  options.params[key];
    }

    options.messages['mycustomvalidation'] = options.message;
});

I can create a custom Data annotation:

Model:

[CustomClientValidation("mycustomvalidation", "value1", "value2", ErrorMessage="validacion propia")]
public string MyProperty { get; set; }

Data annotation:

public class CustomClientValidationAttribute : ValidationAttribute, IClientValidatable
{
    public CustomClientValidationAttribute(string validationType)
    {
        this.ValidationType = validationType;
    }

    public CustomClientValidationAttribute(string validationType, params object[] parameters)
        : this(validationType)
    {
        if (parameters != null && parameters.Count() > 0)
        {
            this.ValidationParameters = new Dictionary<string, object>();
            var countParameters = parameters.Count();
            for (var index = 0; index < countParameters; index++)
            {
                this.ValidationParameters.Add(string.Format("parameter{0}", index), parameters[index]);
            }
        }
    }

    public string ValidationType { get; set; }

    public IDictionary<string, object> ValidationParameters { get; set; }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule()
        {
            ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
            ValidationType = this.ValidationType,
        };

        if (this.ValidationParameters != null)
        {
            foreach (var parameter in this.ValidationParameters)
            {
                rule.ValidationParameters.Add(parameter.Key, parameter.Value);
            }
        }

        yield return rule;
    }

    public override bool IsValid(object value)
    {
        return true;
    }
}

Or with javascript:

$.validator.addMethod('mycustomvalidationii', function(value) {

    if (value.length < 6) {
        return false;
    }

    return true;
}, 'my custom validation');

$("#MyProperty").rules("add", "mycustomvalidationii");
andres descalzo
  • 14,887
  • 13
  • 64
  • 115

1 Answers1

0

You could write a custom validation attribute that will implement the IClientValidatable interface and then register a custom adapter for the client validation. Here's an example that illustrates how you could write such custom validation attribute that will be capable of validating multiple dependent properties and also attach a custom client validation adapter to replicate the same validation logic on the client.

Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928