简体   繁体   中英

Use ASP.NET MVC validation by Jquery

I want to show validation messages for my DOM elements for which the validation are written into Viewmodel:

My viewmodel code is as::

 public class HotelDetailViewModel
    {
        public long DocumentHotelID { get; set; }
        [Required(ErrorMessage = "Please enter Check In Date")]
        public string CheckInDate { get; set; }
        [Required(ErrorMessage = "Please enter Room Type")]
        public string RoomType { get; set; }
        [Required(ErrorMessage = "Please enter Nights")]
        public int Nights { get; set; }
    }

I have also used the Razor Validators as:

@Html.ValidationMessageFor(Model => Model.CheckInDate)

But I want to do the Validation on client side itself, without doing any submit. Because I have two forms on page and only one form can be submitted and for other I haveto do something using Jquery on client side, that I am asking. Thanks in Advance.

To enable eager validation with the jQuery Validation plugin, use this code in your view

$('#myform').validate({
onfocusout: function(element) {
    $(element).valid();
}
});

In MVC, to support DataAnnotation validation on client side, you just have to put this javascript file **jquery.unobtrusive-ajax.js, jquery.validate.min.js, jquery.validate.unobtrusive.min.js

which is can be render as

 @Scripts.Render("~/bundles/jqueryval")

If you are allready using jquery.validate.min.js, you can add validation rules on client side.

<script src="jquery.validate.min.js" type="text/javascript"></script>

Example

@using (Html.BeginForm("action", "controller", new { Id = "ClientForm" }, FormMethod.Post))
{

    @Html.LabelFor(m => m.UserName)
    @Html.TextBoxFor(m => m.UserName)

    <input type="submit" value="Log in" />
}

Add validation rules

<script>
    $("#ClientForm").validate({
        rules: {
            'UserName': {
                required: true,
                maxlength: 20
            }
        },
        messages: {
            'UserName': {
                required: 'Title required',
                maxlength: 'Must be under 20 characters'
            }
        }
    });
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM