-1

I do have created a MVC C# App with a ViewModel which all the properties are [required] and also have created its due View, my problem is that I need to capture the click event from the submit button in order to make some validations so I' decided to use jQuery to capture the click event this way:

 $("#IngresarInfo").click(function (e) {
            e.preventDefault();
            $("#idISSSBuscar").rules("remove", "required");
            $.ajax({ ... some code here

but if I use the e.preventDefault(); the validation [required] does work (doesn´t show any error message) and what i want is first to validate that all the forms inputs are completed and after that make the validation.

could you please tell me what is wrong with my code?

Pablo Tobar
  • 614
  • 2
  • 13
  • 37
  • 1
    `what i want is first to validate that all the forms inputs are completed and after that make the validation.`=>what do you mean by this? – Alive to die - Anant Jul 19 '17 at 13:20
  • `what i want is first to validate that all the forms inputs are completed and after that make the validation` So you want to do the validation before you do the validation...? That doesn't make sense I'm afraid – Rory McCrossan Jul 19 '17 at 13:24
  • @RoryMcCrossan I did write: I need to capture the click event from the submit button in order to make some validations, clear? – Pablo Tobar Jul 19 '17 at 13:26
  • 1
    @Pablo Tobar, it appears that you want to leverage the validation offered by HTML5 as well your own custom validation. What you can do is create a "page sniffer" function that fires on click, that will search for any error element that is generated by the browser. If an error exists, do not fire your custom validation, but if no error occurs, do your validation. – Alexander Dixon Jul 19 '17 at 13:27
  • 1
    You should probably consider creating your own custom attribute if you wish to tap into the existing validation architecture: https://stackoverflow.com/questions/11959431/how-to-create-a-custom-validation-attribute – JuanR Jul 19 '17 at 13:49

1 Answers1

0

Yes, when e.PreventDefault() is called then the default process is stopped. i.e. your server side controller action is not going to get called by default.

From the jQuery documentation

If this method is called, the default action of the event will not be triggered.

If you want to continue on to the controller action after call e.PreventDefault, you'll need to submit the form yourself.

Another question. why do this at all? If you left MVC to do its default validation of the viewmodel, you can look for Model.IsValid in your post action and return the original view with the validation errors.

It seems like you are trying to mimic this exact behavior, but I don't know what you gain by it.

Fran
  • 6,440
  • 1
  • 23
  • 35
  • Thanks, I want to do it this way because a teammate achieve to do it and I wrote exactly the same code with my logic but didn't works – Pablo Tobar Jul 19 '17 at 13:30