Hỏi đáp

Chia sẻ kiến thức, cùng nhau phát triển

Giúp mình sửa validate ngày tháng trong asp.net mvc

10:34 05-10-2017 4.878 lượt xem 3 bình luận 11:42 05-10-2017

model
 

[Required(ErrorMessage = "Yêu cầu nhập ngày")]
        [DataType(DataType.Date)]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
        public Nullable<System.DateTime> createDate { get; set; }

 

View:

<div class="col-sm-3">
            <div class="form-group">
                <div class="input-group date">

                    @Html.TextBoxFor(model =>model.createDate, new { htmlAttributes = new { @class = "form-control form-input datepicker" } })
                    @Html.ValidationMessageFor(model => model.createDate, "", new { @class = "text-danger" })                    
                    <span class="input-group-addon invisible"><i class="glyphicon glyphicon-th"></i></span>
                </div>
            </div>
        </div>  

Jquery
 

 $('.input-group.date').datepicker({
            format: 'dd/mm/yyyy'
        });

khi nhập vào ngày
1/10/2017 thì ok nhưng nhập 28/10/2017 thì nó hiểu 28 là tháng nên báo lỗi The value '28/10/2017' is not valid for createDate.
có ai rành fix dùm mình với ạ

Bình luận

Để bình luận, bạn cần đăng nhập bằng tài khoản Howkteam.

Đăng nhập
Nguyen Van Tung đã bình luận 11:42 05-10-2017

Mình sửa được rồi, đây là code 
View:

@Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    <div class="row">
        <div class="col-sm-3 text-right"><div class="form-control" style="border:0; box-shadow:none">Ngày nạp tiền</div></div>
        <div class="col-sm-3">
            <div class="form-group">
                <div class="">
                    @Html.EditorFor(model =>model.createDate, new { htmlAttributes = new { @class = "form-control form-input" } })
                    @Html.ValidationMessageFor(model => model.createDate, "", new { @class = "text-danger" })                    
                    <span class="input-group-addon invisible"><i class="glyphicon glyphicon-th"></i></span>
                </div>
            </div>
        </div>
    </div>

Model:

[Required(ErrorMessage = "Yêu cầu nhập ngày")]
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{dd/mm/yyyy}")]
        public Nullable<System.DateTime> createDate { get; set; }

khi dùng
 

[DisplayFormat(DataFormatString = "{dd/mm/yyyy}")]

thì trong view chỉ được dùng  EditorFor / DisplayFor chứ không được dùng:  TextBoxFor
và khi đã dùng DisplayFormat rồi thì trong view các bạn không cần dùng jquery để chạy datepicker nữa

K9 SuperAdmin, KquizAdmin, KquizAuthor đã bình luận 11:08 05-10-2017

bạn coi kỹ chỗ này

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]

 

Câu hỏi mới nhất