4

I have a sample application, trying to learn jQuery validation and submit form in this scenerio.

The page has one text box (EnvelopeID per class Envelope). If submit button is clicked and the text box is empty then i want to show an error message. If it is not empty then i want to post ajax request to GetData Action. The action returns partial views (value 1 or 2) or error string.

Problem:

  1. Client validation is not happening here.
  2. How can i make $(form).submit to adhere to jquery validation and not post the data if empty? I can check for text box being empty or not before posting (manually) but i want to use the proper way.

This same very example works with MSAjax and validation without any problem.

Master Page Head

<script type="text/javascript" src="<%= Url.Content("~/Scripts/jquery-1.4.1.min.js") %>"></script>
<script type="text/javascript" src="<%= Url.Content("~/Scripts/jquery.validate.min.js") %>"></script>
<script type="text/javascript" src="<%= Url.Content("~/Scripts/MicrosoftMvcJQueryValidation.js") %>"></script>

Class:

namespace PartialViews.Models
    {
        public class Envelope
        {
            [Required(ErrorMessage="Envelope ID is required!")]
            public string EnvelopeID { get; set; }
        }
    }

Data Action:

[HttpPost]
public ActionResult GetData(Envelope envelope)
{
    ActionResult result = null;
    if (ModelState.IsValid)
    {
        Information myInfo = newInformation();
        if (envelope.EnvelopeID == "1")
        {
            result = View("TQ1PV", myInfo); //partial view
        }
        elseif (envelope.EnvelopeID == "2")
        {
            result = View("TQ2PV", myInfo); //partial view
        }
        else
        {
            result = Content("Error");
        }
    }
    else
    {
        result = View("index", envelope);
    }
    return result;
}

Index Action:

public Action Result Index()
{
    return View();
}

JS on View - Index

<script type="text/javascript">
    $(function () {
        //onload 
        $("#evid").focus();
        $("form[name='EVIDForm']").submit(function () {
            var action = $(this).attr('action');
            var evid = $("#evid").val();
            var tdata = $(this).serialize();
            alert(tdata);
            $message = $("#resultDiv");
            $message.html('').removeClass("red");
            $.ajax({
          cache: false, 
          type: "post",
          url: action,
          data: tdata,
          dataType: "html",
          error: function (xhr, ajaxOptions, thrownError){ 
                    alert('system error');
                },
                success: function(data){
           if (data == 'Error')
                        $message.html("No such EV ID found!").addClass("red");
                    else
                        $message.html(data);
          }
         });
            return false;
        });
    });

</script>

HTML on View - Index:

    <% Html.EnableClientValidation(); %>
    <%= Html.ValidationSummary() %>

    <% using (Html.BeginForm("GetData", "Info", FormMethod.Post, new {name = "EVIDForm" }))
       {%>
       <%= Html.LabelFor(model => model.EnvelopeID) %> &nbsp;&nbsp;
       <%= Html.TextBoxFor(model => model.EnvelopeID, new { maxlength = "8"})%>
       <%= Html.ValidationMessageFor(model => model.EnvelopeID,"*") %>
       <br /><br />


        Correct EVIDs are 1 and 2. All other entries will result in an error.
        <br /><br />
        <input type="submit" value="submit" />
    <%} %>
    <div id="resultDiv" style="margin-top: 20px;"></div>

Thanks

Rashmi Pandit
  • 23,230
  • 17
  • 71
  • 111
learning...
  • 3,104
  • 10
  • 58
  • 96
  • I have almost the same problem as described in the post that @vandalo linked. It seems that the client validation does not work without submitting the form. But If I have to submit the form the validation is not anymore client side.... I did not receive an answer to my question here: `http://stackoverflow.com/questions/4172319/inline-client-side-validation-with-mvc-and-jquery/` – Lorenzo Nov 16 '10 at 14:13
  • @Lorenzo: the form is not submitted. You can try and set a breakpoint in the controller receiving the post. It will never trigger. The only problem is (only the first time, until you don't click the button) the client-side validation doesn't seem to trigger from the very beginning. – LeftyX Nov 16 '10 at 14:40
  • @vandalo: If you use fiddler or firebug you can see the submit to the server – Lorenzo Nov 16 '10 at 14:47

4 Answers4

0

I would suggest you to do something I've described here

Community
  • 1
  • 1
LeftyX
  • 35,328
  • 21
  • 132
  • 193
0

http://geekswithblogs.net/stun/archive/2010/02/27/asp.net-mvc-client-side-validation-summary-with-jquery-validation-plugin.aspx

And if you want to see the full javascript, I have my version posted in a question I posted jquery.validate lost on ajax replacement and only showing last error

This is how to make it work with the validation summary, but perhaps it can help you figure out your problem. I do know that if you are referencing the microsoft validation javascript and the jquery validation javascript files, they will cause issues with one another.

Community
  • 1
  • 1
Josh
  • 16,286
  • 25
  • 113
  • 158
0

Maybe you can use this for validate all input fields:

Simple but powerful jquery form validation

Regards...

pacoespinoza
  • 121
  • 4
0

<% using (Html.BeginForm("Register", "User", FormMethod.Post, new { id = "RegisterForm" }))

 $("#RegisterForm").validate({

            rules: {
                ignore: ":not(:visible)",
                EmailAddress: {
                    required: true,
                    email: true
                },
                ConfirmEmailAddress: {
                    required: true,
                    email: true,
                    equalTo: "#EmailAddress"
                },
                Password: {
                    required: true
                },
                ConfirmPassword: {
                    required: true,
                    equalTo: "#Password"
                }
            },
            messages: {
                EmailAddress: {
                    required: " Email Address is required",
                    email: " Email Address is invalid"
                },
                ConfirmEmailAddress: {
                    required: " Email Address is required",
                    email: " Email Address is invalid",
                    equalTo: "Enter Email Address same as above"
                },
                Password: {
                    required: " Password is required"
                },
                ConfirmPassword: {
                    required: " Password is required",
                    equalTo: " Enter Confirm Password same as above"
                }
            }
        });
yogeswaran K
  • 2,278
  • 8
  • 29
  • 45