Sumesh Kuttan
Sumesh Kuttan

Reputation: 1353

Change ASP.NET MVC validation dynamically in Jquery

On one of the view model fields, I have set the min length in ASP.NET MVC Data Annotation attribute.

[MinLength(5, ErrorMessage = "A minimum of 5 digits is required")]

Based on a dropdown selection(which has 2 values), MinLength needs to be updated to 10. ClientSideValidation is enable and so validation needs to reflect the changes before it is posted back to the controller.

Tried changing the attribute "data-val-minlength-min" using jQuery based on dropdown value, but it did not change the validation.

Any suggestions please.

Upvotes: 3

Views: 1495

Answers (2)

Sumesh Kuttan
Sumesh Kuttan

Reputation: 1353

@StephenMuecke gave me the solution I needed. It works on client side and server side as desired. I am posting it as answer so that the next person can easily see it.

Create you own conditional validation attribute so that you get both client and server side validation - The Complete Guide To Validation In ASP.NET MVC 3 - Part 2

Upvotes: 0

Hari Gillala
Hari Gillala

Reputation: 11916

Try this approach. This is to use RemoteValidations for more than one fields in the model.

[Remote("CheckForSelectedDropDownLengthMethod","ControllerName",AdditionalFields="SelectedDropDownName",ErrorMessage="The length should be be 10 characters.")]

public class ControllerName: Controller
{
    public JsonResult CheckForSelectedDropDownLengthMethod(Model yourmodel)
        {
              // write your logic to validate the logic here ,
              // Get the selected value of the dropdown, and the field where you want to check the length.
        }
}

Please follow one of the example https://www.codeproject.com/Tips/669824/Implementing-Remote-Validation-in-MVC

Upvotes: 1

Related Questions