locked
How to create Custom Hijri Date Validation in MVC 5? RRS feed

  • Question

  • User-1042970710 posted

    Hi Guys,

    I have custom Hijri Date  coming from the MVC View  format: (DD-MM-YYYY)  example: 01-01-1441   (Date coming as String) From HTML Control

    I want to Validate this date using a custom function I have which I used in classic ASP.NET Forms in custom Control. The function works perfectly fine to validate the hijri date.

    using System;
    using System.Globalization;
    
    
      public static bool IsValidHijriDate(string pHijri)
            {
                Int64 tempObject;
                if (!Int64.TryParse(pHijri, out tempObject))
                {
                    return false;
                }
    
    
                bool _result;
                DateTime dt = new DateTime();
                DateTime.TryParseExact(pHijri, "yyyyMMdd", ciHijriFormat1, DateTimeStyles.None, out dt);
                try
                {
                    string str = dt.ToString("yyyyMMdd", ciHijriFormat1);
                }
                catch
                {
                    dt = DateTime.MinValue;
                }
                _result = dt != DateTime.MinValue;
    
                //there was validating error for date > 1448
                if (!_result)
                {
                    if (pHijri.Length == 8)
                    {
                        if ((Convert.ToInt32(pHijri.Substring(0, 4)) > 1448) & (Convert.ToInt32(pHijri.Substring(0, 4)) < 1580))
                        {
                            _result = true;
                        }
                    }
                }
                return _result;
            }

    Can Any one tell me how I can use this function  to create custom Hijri Date Validator in MVC which I can apply directly to my Model (POCO) class? 

    I am using ASP.NET MVC 5 

    Thanks.

    Imran Jalali.

    Thursday, April 9, 2020 6:22 AM

Answers

  • User665608656 posted

    Hi jalali,

    If you want to apply custom code validation to your model, you can create a class named "ValidHijriDateAttribute" and inherit from "ValidationAttribute", rewriting the "IsValid" method using your custom method. 

    Then you only need to add data verification to the field that needs to be verified.

    More details, you could refer to below code:

       public class ValidHijriDateAttribute : ValidationAttribute
            {
                //create for testing
                private static IFormatProvider ciHijriFormat1;
                public override bool IsValid(object value)
                {
                    return IsValidHijriDate(value.ToString());//Call custom method
                }
                public bool IsValidHijriDate(string pHijri)
                {
                    Int64 tempObject;
                    if (!Int64.TryParse(pHijri, out tempObject))
                    {
                        return false;
                    }
    
                    bool _result;
                    DateTime dt = new DateTime();
                    DateTime.TryParseExact(pHijri, "yyyyMMdd", ciHijriFormat1, DateTimeStyles.None, out dt);
                    try
                    {
                        string str = dt.ToString("yyyyMMdd", ciHijriFormat1);
                    }
                    catch
                    {
                        dt = DateTime.MinValue;
                    }
                    _result = dt != DateTime.MinValue;
    
                    //there was validating error for date > 1448
                    if (!_result)
                    {
                        if (pHijri.Length == 8)
                        {
                            if ((Convert.ToInt32(pHijri.Substring(0, 4)) > 1448) & (Convert.ToInt32(pHijri.Substring(0, 4)) < 1580))
                            {
                                _result = true;
                            }
                        }
                    }
                    return _result;
                }
            }

    User.cs:

    public class User
        {
            [Key]
            public string UserId { get; set; }
            [ValidHijriDate]
            public string UserDate { get; set; }
    
        }

    Controller:

    public class HomeController : Controller
        {
            private ValidHijriDate db = new ValidHijriDate();
            public ActionResult Index()
            {
                return View();
            }
    
            [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult Index([Bind(Include = "UserId,UserDate")] User user)
            {
                if (ModelState.IsValid)
                {
                    user.UserId = Guid.NewGuid().ToString();
                    db.Users.Add(user);
                    db.SaveChanges();
                }
                return View(user);
            }
    
    }

    View:

    @model Test.Models.User
    
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
        <hr />
        <div class="form-horizontal  col-md-offset-3">
            <div class="form-group">
                @Html.LabelFor(model => model.UserDate, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.UserDate, new { htmlAttributes = new { @class = "form-control col-md-offset-1" } })
                    @Html.ValidationMessageFor(model => model.UserDate, "", new { @class = "text-danger" })
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Register" class="btn btn-primary btn-block" />
                </div>
            </div>
        </div>
    }

    Here is the result :

    Best Regards,

    YongQing.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, April 10, 2020 5:19 AM

All replies

  • User475983607 posted

    I want to Validate this date using a custom function I have which I used in classic ASP.NET Forms in custom Control. The function works perfectly fine to validate the hijri date.

    Just copy and paste the code into your controller or class and call the method.  However, the IsValidHijriDate does not validate dates formatted as dd-MM-YYYY.  So it's very confusing why you think it works... 

    Thursday, April 9, 2020 10:20 AM
  • User665608656 posted

    Hi jalali,

    If you want to apply custom code validation to your model, you can create a class named "ValidHijriDateAttribute" and inherit from "ValidationAttribute", rewriting the "IsValid" method using your custom method. 

    Then you only need to add data verification to the field that needs to be verified.

    More details, you could refer to below code:

       public class ValidHijriDateAttribute : ValidationAttribute
            {
                //create for testing
                private static IFormatProvider ciHijriFormat1;
                public override bool IsValid(object value)
                {
                    return IsValidHijriDate(value.ToString());//Call custom method
                }
                public bool IsValidHijriDate(string pHijri)
                {
                    Int64 tempObject;
                    if (!Int64.TryParse(pHijri, out tempObject))
                    {
                        return false;
                    }
    
                    bool _result;
                    DateTime dt = new DateTime();
                    DateTime.TryParseExact(pHijri, "yyyyMMdd", ciHijriFormat1, DateTimeStyles.None, out dt);
                    try
                    {
                        string str = dt.ToString("yyyyMMdd", ciHijriFormat1);
                    }
                    catch
                    {
                        dt = DateTime.MinValue;
                    }
                    _result = dt != DateTime.MinValue;
    
                    //there was validating error for date > 1448
                    if (!_result)
                    {
                        if (pHijri.Length == 8)
                        {
                            if ((Convert.ToInt32(pHijri.Substring(0, 4)) > 1448) & (Convert.ToInt32(pHijri.Substring(0, 4)) < 1580))
                            {
                                _result = true;
                            }
                        }
                    }
                    return _result;
                }
            }

    User.cs:

    public class User
        {
            [Key]
            public string UserId { get; set; }
            [ValidHijriDate]
            public string UserDate { get; set; }
    
        }

    Controller:

    public class HomeController : Controller
        {
            private ValidHijriDate db = new ValidHijriDate();
            public ActionResult Index()
            {
                return View();
            }
    
            [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult Index([Bind(Include = "UserId,UserDate")] User user)
            {
                if (ModelState.IsValid)
                {
                    user.UserId = Guid.NewGuid().ToString();
                    db.Users.Add(user);
                    db.SaveChanges();
                }
                return View(user);
            }
    
    }

    View:

    @model Test.Models.User
    
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
        <hr />
        <div class="form-horizontal  col-md-offset-3">
            <div class="form-group">
                @Html.LabelFor(model => model.UserDate, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.UserDate, new { htmlAttributes = new { @class = "form-control col-md-offset-1" } })
                    @Html.ValidationMessageFor(model => model.UserDate, "", new { @class = "text-danger" })
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Register" class="btn btn-primary btn-block" />
                </div>
            </div>
        </div>
    }

    Here is the result :

    Best Regards,

    YongQing.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, April 10, 2020 5:19 AM