0

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.

3 Answers 3

1

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

$('#myform').validate({
onfocusout: function(element) {
    $(element).valid();
}
});
Sign up to request clarification or add additional context in comments.

Comments

0

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")

2 Comments

Read the question properly and then answer.
This javascript file will validate model, without submitting
0

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>

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.