Ananda Sudarshan
Ananda Sudarshan

Reputation: 485

custom model validation using data annotations MVC3 | error messages not shown on client side though properties are added and jquery written

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

Upvotes: 1

Views: 888

Answers (2)

Ananda Sudarshan
Ananda Sudarshan

Reputation: 485

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.

Upvotes: 0

Sergey Barskiy
Sergey Barskiy

Reputation: 1803

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

Upvotes: 1

Related Questions