1

I'm working on a MVC App and I need to check if a user is registered, for that purpose I've created a model

public class Ejemplo
 {
   [Required(ErrorMessage="Favor especificar Username")]
   [DataType(DataType.Text)]
   public string usuario { get; set; }

   [Required(ErrorMessage="Favor especificar password")]
   [DataType(DataType.Password)]
   public string password { get; set; }
 }

my problem so far is that I need to send the info of the user in a JSON format via AJAX and I need to validate that the username and password info are specified, in order to accomplish that I' coded this:

<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script src="~/Scripts/jquery-1.10.2.js"></script>
    <script src="~/Scripts/jquery.validate.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
    <script type="text/javascript">
    $(document).ready(function () {

        $('#myform').validate({ // initialize the plugin
            rules: {
                usuario: {
                    required: true,
                    minlength: 12
                },
                password: { required: true }
            },
            messages: {
                usuario: {
                    required: "must specify username --> validate !!!",
                    minlength: "not a valid Lenght --> validate !!!"
                },
                password: {
                    required: "must specify a password --> validate !!!"
                }
            },
             submitHandler:
                    $("#myform").on('submit', function () {
                        alert("have just pressed submit");
                        if ($("#myform").valid()) {
                            alert("here some code inside $.AJAX({})");
                        }
                        return false;
                    })
        })
    });

and this is my form(the code above and the form are in the same file: Index.cshtml)

<fieldset>
 <legend> Validaciones MVC </legend>
  @using (Html.BeginForm("Prueba", "Prueba", FormMethod.Post, new { @id = "myform" }))
  {

     @Html.LabelFor(M => M.usuario);
     <br />
     @Html.EditorFor(M=>M.usuario)
     @Html.ValidationMessageFor(M => M.usuario);
     <br />
     @Html.LabelFor(M=>M.password)
     <br />
     @Html.EditorFor(M=>M.password);
     @Html.ValidationMessageFor(M=>M.password)
     <br />
     <br />

  <input type="submit" id="boton_id" name="boton_name" value="Enviar" />
                }
        </fieldset>

but it doesn't validate and doesn't show any message in case the username and password are empty, it only shows this alert: alert("have just pressed submit"); but never shows the second alert: alert("here some code inside $.AJAX({})"); this two alert are in

submitHandler:
                    $("#myform").on('submit', function () {
                        alert("have just pressed submit");
                        if ($("#myform").valid()) {
                            alert("here some code inside $.AJAX({})");
                        }
                        return false;
                    })

so, could you please help me and tell me where is my problem or what I' missing please?

2 Answers 2

1

First off, your JavaScript for calling validate is syntactically incorrect. You need to wrap the submitHandler code in a function:

submitHandler: function () { .... }

Next, submitHandler is already called when the submit event is triggered (and when the form is valid). You do not need to bind another event handler or check if the form is valid inside of submitHandler.

per the documentation:

Callback for handling the actual submit when the form is valid. Gets the form as the only argument. Replaces the default submit. The right place to submit a form via Ajax after it is validated.

The following should suffice:

submitHandler: function () {
    // Submit the form via AJAX.
}
Sign up to request clarification or add additional context in comments.

10 Comments

Hello. I' just made the change and now it looks like: submitHandler: function () { alert("have just pressed submit"); } but it still doesn't validate if the fields are empty
@PabloTobar: Are there any JavaScript errors on the page?
Hello @Andrew, No Sr, not any problem, do I have to specify the id of my form inside submitHandler: Function( here the id ) ?
@PabloTobar: Nope... that should work. Have you debugged your code to make sure the .validate call is being executed?
@PabloTobar: Hmm, you could try removing unobtrusive validation <script src="~/Scripts/jquery.validate.unobtrusive.js"></script>. It could be causing conflicts
|
1

I'd like to add supplementary information related to @AndrewWhitaker comment:

Hmm, you could try removing unobtrusive validation . It could be causing conflicts.

It's indeed an issue because jquery.validate.unobtrusive.js creates validator internally and associates it with the form. Next, when your below code is invoked:

$(document).ready(function () {
    $('#myform').validate({ // initialize the plugin

what jquery.validate.js actually does, is following:

validate: function( options ) {
    ...
    // check if a validator for this form was already created
    var validator = $.data(this[0], 'validator');
    if ( validator ) {
        return validator;
    }

As you can see, it just checks if there is a validator associated with your form. If yes, it is simply returned (your initialization settings are irrelevant in that case).

What you could do here (instead removing of jquery.validate.unobtrusive.js, unless you don't need it), is to access and change the validator settings directly, e.g.

var validator = $('#myForm').validate();
validator.settings.submitHandler = function(form) { ...
// etc.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.