1

I have implimented a custom validation using data annotation on model, MVC 3. Also imlimented jquery and scripts for unobstrusive client validation of the same, taken care to over ride the

public override IEnumerable<ModelClientValidationRule> GetClientValidationRules() as well. but still error message and styling not shown for wrong values.

I checked my scripts and the jquery, they are being registered (placed alerts in them to confirm).

please help.

Server side code below

    public class SQLInjectionAttribute : ValidationAttribute
{
    private readonly string[] CheckParametersToValidateAgainst = ConfigurationManager.AppSettings["SQLINJECTIONCHARACTERS"].ToString().Split(' ');

    public SQLInjectionAttribute()
    {

    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value != null)
        {

            if (CheckIfValidSafeString((string)value))
            {
                return new ValidationResult("blah blah");   
            }
        }
        return ValidationResult.Success;
    }

    private bool CheckIfValidSafeString(string SampleString)
    {            

        foreach (string CheckParameter in CheckParametersToValidateAgainst)
        {
            if(SampleString.ToLower().Contains(CheckParameter))
            {
                return false;
            }
        }

        return true;
    }
}



/// </summary>
public class SQLInjectionValidator : DataAnnotationsModelValidator<SQLInjectionAttribute>
{
    string CheckParametersToValidateAgainst = ConfigurationManager.AppSettings["SQLINJECTIONCHARACTERS"].ToString();
    string errorMsg = string.Empty;

    public SQLInjectionValidator(ModelMetadata metadata, ControllerContext context, SQLInjectionAttribute attribute)
        : base(metadata, context, attribute)
    {
        errorMsg = attribute.ErrorMessage;
    }

    /// <summary>
    /// The class 'ModelClientValidationRule' is a base class container for client validation rule sent to the browser.
    /// </summary>
    /// <returns></returns>
    public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
    {
        ModelClientValidationRule validationRule = new ModelClientValidationRule();
        validationRule.ErrorMessage = errorMsg;
        validationRule.ValidationType = "sqlinjectionvalidator";
        validationRule.ValidationParameters.Add("parameterstovalidateagainst", CheckParametersToValidateAgainst);
        return new[] { validationRule };

    }
} 

The JQuery scripts are as below .

'`

(function ($) {

var isValid =  function (value, element, params) {

        var str = "; \' -- /* */ xp_";
        var parametersToValidateAgainst = str.split(" ");

        for (i = 0; i < parametersToValidateAgainst.length; i++) {
            if (value.indexOf(parametersToValidateAgainst[i]) != -1) {
             alert('false');   
                return false;
            }


        }
         alert('true');   
        return true;
    }

    $.validator.addMethod("sqlinjectionvalidator", isValid)

    $.validator.unobtrusive.adapters.add("sqlinjectionvalidator", ["parameterstovalidateagainst"],
    function (options) {
    debugger;
    alert('adapter added');
        options.rules['sqlinjectionvalidator'] = {
            parameterstovalidateagainst: options.params.parameterstovalidateagainst,               
        };
        options.messages['sqlinjectionvalidator'] = options.message;
    });


} (jQuery));

`

Thanks in advance

Anand

1

2 Answers 2

1

Maybe you are replacing HTML? In that case you need to call jQuery.validator.unobtrusive.parse(‘form’); after you update html.

1
  • Thanks for the thoughts Sergy, My HTML are static. also i just stumbled upon the reason for my client validation failing, PFB Dec 28, 2011 at 6:22
0

Thanks for all the support !

Finally found the answer to this ! The jquery scripts used are ver 1.5.1 that has some bugs handling the custom validators at client end.

ran nuget package upgrade and updated to 1.6.1 and it is working good.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.