jonny
jonny

Reputation: 797

Validation not working mvc 3 properly

I am working on a project and i have some problem with my validation Here is my model:

[ColumnMap("Guest_ID")]
public int Guest_ID { get; set; }

[ColumnMap("FirstName")]
[Required]
[Display(Name="FirstName")]
public  string FirstName { get; set; }

[ColumnMap("LastName")]
public string LastName { get; set; }

[ColumnMap("Phone")]
[Required]  
[MaxLength(10)]
public Nullable<int> Phone { get; set; }

[ColumnMap("AdrOras")]
[Required]
public string AdrOras { get; set; }

So I have required on FirstName and Phone and also MaxLength=10 on Phone.

Here is my CreateReservation method in my controller:

public ActionResult CreateReservation(int? RoomID, string FirstName, string LastName,int? Phone,string Oras,string Judet,string Tara,string Strada,int? GuestTypeId,DateTime? Birthday,DateTime? Data_Check_in, DateTime? Data_Check_out) 
{
    DBContext.Current.Open();
    Reservation rezervare = new Reservation();
    string  username= User.Identity.Name;
    Users user=Users.UserbyUsername(username);
    if(!string.IsNullOrEmpty(RoomID.ToString())&&!string.IsNullOrEmpty(FirstName)&&!string.IsNullOrEmpty(LastName)&&Phone.HasValue&&!string.IsNullOrEmpty(Judet)&&!string.IsNullOrEmpty(Tara)&&!string.IsNullOrEmpty(Strada)&&!string.IsNullOrEmpty(GuestTypeId.ToString())&&Birthday.HasValue&&Data_Check_in.HasValue&& Data_Check_out.HasValue)
    {
        rezervare.CreazaRezervare(RoomID, FirstName, LastName, Phone, Oras, Judet, Tara, Strada, GuestTypeId, Birthday,user.UserID,Data_Check_in, Data_Check_out);
        return RedirectToAction("MyReservation","Reservation");
    }

    var model = GuestTyp.SelectAll();
    ReservationView rez = new ReservationView()

    {
        rezervare =rezervare,
        client = model.ToList()
    };

    DBContext.Current.Close();
    return View(rez);
}

And here is my view :

@model LicentaTest.Models.ReservationView
@using JQueryUIHelpers

@{
    ViewBag.Title = "Checkout";
}

<head>
    <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
    <script src="../../Scripts/jquery-ui-1.8.19.min.js" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery-ui.unobtrusive.min.js")" type="text/javascript"></script>   
    <script src="../../Scripts/jquery-ui.unobtrusive-0.5.0.min.js" type="text/javascript"></script>
</head>

<script type="text/javascript">
    $(function () {
        $('input[type=text], textarea, input[type=password]').width(200);
        $('#valSum').hide();
        $('form').bind('invalid-form.validate', function (error, element) {
            $('#valSum').show("slow");
            return false;
        });
    });
</script>

@if (!ViewData.ModelState.IsValid) {
    <script type="text/javascript">
        $(function () {
            $('#valSum').show("slow");
        });
    </script>
}

@using (Html.BeginForm("CreateReservation", "Reservation", FormMethod.Post))
{
    @Html.ValidationSummary(true)
    <form class="form">
    <div class = "styler">
    <div id = "valSum" class="ui-state-error ui-corner-all" style="padding: 0 .7em;width:500px">    
</div>
    <h6>Completare Date Rezervare</h6>
    <fieldset class="ui-widget">
        <legend class="ui-state-legend-default ui-corner-top ui-corner-bottom">Date personale</legend>
            @Html.Hidden("RoomID")  
            <div class="editor-label">
                @Html.Label("FirstName")
                @Html.TextBox("FirstName") 
                @Html.ValidationMessage("FirstName","Numele trebuie introdus")
            </div>
            <div class="editor-label">
                @Html.Label("LastName    ")
                @Html.TextBox("LastName") 
            </div>
            <div class="editor-label">
                @Html.Label("Phone")
                @Html.TextBox("Phone")  
                @Html.ValidationMessage("Phone","Numarul trebuie sa fie din maxim 10 cifre")
            </div>
            <div class="editor-label">
                @Html.Label("Data Nasterii")
                @(Html.JQueryUI().Datepicker("Birthday").MaxDate(DateTime.Now))
            </div>
            <div class="editor-label">
                @Html.Label("Tip CLient")
                @Html.DropDownList("GuestTypeID", new SelectList(Model.client.AsEnumerable(), "GuestTypeID", "GuestType"))
            </div>
        </fieldset>
    <fieldset class="ui-widget">
    <legend class="ui-state-legend-default ui-corner-top ui-corner-bottom">Adresa</legend>
        <div class="editor-label">
            @Html.Label("Tara")
            @Html.TextBox("Tara")
        </div>
        <div class="editor-label">
            @Html.Label("Oras")
            @Html.TextBox("Oras")
            @Html.ValidationMessage("Oras","Field is required")
        </div>
        <div class="editor-label">
            @Html.Label("Judet")
            @Html.TextBox("Judet")
        </div>
        <div class="editor-label">
            @Html.Label("Strada")
            @Html.TextBox("Strada")
        </div>
    </fieldset>
    <fieldset class="ui-widget">
        <legend class="ui-state-legend-default ui-corner-top ui-corner-bottom">Perioada rezervare</legend>
        <div class="editor-label">
            @Html.Label("Data Intrare")
            @Html.JQueryUI().Datepicker("Data_Check_in")
        </div>
        <div class="editor-label">
            @Html.Label("Data Iesire")
            @Html.JQueryUI().Datepicker("Data_Check_out")
        </div>
    </fieldset>

    <p>
        <input type="submit" value="Create" />
    </p>

    <div>
        @Html.ActionLink("Back to List", "Index", "Guest")
    </div>
    </div>
    </form>
}

When i push create button the maxlenght validation is working but the required field validation is not working enter image description here

Why is this happening what am i doing wrong

Upvotes: 4

Views: 1440

Answers (2)

pollirrata
pollirrata

Reputation: 5286

You may want to create a ViewModel for that creation screen (Unless I'm wrong you're using more fields than the ones you have in your model, if not you can also receive the Model instance on the Controller instead of each field), so you pass a single object (instance) on the CreateReservation method. This will make things easier for you, and also you shall receive all the values correctly using @Html.TextBoxFor

Also, for checking what are you receiving on the Controller you can add a parameter of FormCollection type. With this you will be able to see each field that is being sent to the Controller

Edited:

After checking everything is OK according to the text above and add (if not yet) the DataAnnotations for the fields, you will be able to use javascript validations; you can check this post or this one that goes deeper

Upvotes: 1

CD Smith
CD Smith

Reputation: 6607

You have 2 forms nested inside each other. You cannot have nested forms.

You have:

@using (Html.BeginForm("CreateReservation", "Reservation", FormMethod.Get)){
    <form>...</form>
}

Remove the <form></form> tags

Also... I don't see a script tag for jQuery in your head section

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.8.19.min.js" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-ui.unobtrusive.min.js")" type="text/javascript"></script>   
<script src="../../Scripts/jquery-ui.unobtrusive-0.5.0.min.js" type="text/javascript"></script>

Try this...

Get jQuery and jQuery UI from CDN

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js" type="text/javascript"></script>

Then these three need to be in this order. And ALWAYS use @Url.Content(...) for your scripts

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>

Upvotes: 4

Related Questions