jwaliszko / ExpressiveAnnotations

Annotation-based conditional validation library.
MIT License
351 stars 124 forks source link

Custom methods not working #205

Closed dkhalil1994 closed 4 years ago

dkhalil1994 commented 4 years ago

Hi, First of all thank you for this library it has helped me alot. It has been working apart from the custom methods, i have a simple method in my model class:

public bool IsValidCanadianSIN(string SIN) // model-level method { return Regex.IsMatch(SIN, @"^(\d{3}-\d{3}-\d{3})|(\d{9})$"); }

but it always returns false doesn't matter if i provide the correct input or not:

[AssertThat("IsValidCanadianSIN(SIN)", ErrorMessageResourceName = "EnterValidSIN", ErrorMessageResourceType = typeof(CommonResource))] public string SIN { get; set; }

image

Maybe i'm missing something, any help would be appreciated thanks!

okankocyigit commented 4 years ago

I think you just implement the server-side validation and looking for client side validation.

As it mentioned in docs, you also have to add client side validation method to get it work properly.

ea.addMethod('IsValidCanadianSIN', function (sin) {
       return /^(\d{3}-\d{3}-\d{3})|(\d{9})$/.test(sin);
});
dkhalil1994 commented 4 years ago

Thank you for your reply, it works perfectly on client side, however is there any way to make this validation work on the server side only. Since i have to fine tune a method for validation and i don't want to have it implemented in jquery. Here is my method:

public static bool IsValidSIN(string SIN) { String wNAS = SIN.Replace(" ", ""); String wNASMult = "121212121"; int wMult; int wSumMult = 0;

        if (wNAS.Length < 9)
        {
            return false;
        }

        for (int i = 0; i < wNAS.Length; i++)
        {
            wMult = Convert.ToInt32(wNASMult.Substring(i, 1)) * Convert.ToInt32(wNAS.Substring(i, 1));
            if (wMult > 9)
            {
                string wTmp = wMult.ToString();
                wSumMult += Convert.ToInt32(wTmp.Substring(0, 1)) + Convert.ToInt32(wTmp.Substring(1, 1));
            }
            else
            {
                wSumMult += wMult;
            }
        }

        return (wSumMult % 10) == 0;
    }

This is what my Global.asax file looks like, i have commented out the code to enable client side validation:

image

okankocyigit commented 4 years ago

you can disable client-side validation for that specific field,

@Html.TextBoxFor(model => model.SIN, new { data_val="false" })

But this also disables other validations which might work client-side like required.

To avoid this, you can just return true from custom client-side validation method, so it will always pass client-side validation.

ea.addMethod('IsValidCanadianSIN', () => true)

dkhalil1994 commented 4 years ago

Awesome! this works exactly the way i want it to.