locked
How to Handle No Required Field? In MVC RRS feed

  • Question

  • User-1042970710 posted

    Folks,

    In  my POCO class  I have defined a non mandatory field.... (i.e I didn't put Required Validator Data Annotation)  

      [ValidHijriDateAttribute]
       public string DecisionDate { get; set; }

    But I want my user  to ignore the Desision Date  field if he don't have it but in case he have it I must validate date in my Custom Validator...

    How I can achive that?

    Saturday, April 18, 2020 6:00 AM

Answers

  • User-1330468790 posted

    Hi jalali,

     

    You can just validate this field and allow the value to be null.

     

    More details, you can refer to below code.

    About cshtml:

    @model MVCCaseDemo.Models.POCO
    
    @{
        ViewBag.Title = "About";
    }
    <h2>@ViewBag.Title.</h2>
    <h3>@ViewBag.Message</h3>
    
    <p>Use this area to provide additional information.</p>
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
    
        <div class="form-horizontal">
            <h4>POCO</h4>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.DecisionDate, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.DecisionDate, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.DecisionDate,"",new { @class = "text-danger" })
                </div>
            </div>
    
            
    
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Create" class="btn btn-default" />
                </div>
            </div>
        </div>
    }

    POCO class:

    public class POCO
        {
            [ValidHijriDateAttribute(ErrorMessage = "The DecisionDate must be in format of yyyy - MM - dd or dd / MM / yyyy")]
            public string DecisionDate { get; set; }
        }

     Controller:


    public ActionResult Index()
    {
    return View();
    }

    [HttpGet] public ActionResult About() { return View(); } [HttpPost] public ActionResult About(POCO poco) { if (ModelState.IsValid) { return RedirectToAction("Index"); } return View(); }

    ValidHijriDateAttribute class:

    public class ValidHijriDateAttribute : ValidationAttribute
        {
            public override bool IsValid(object value)
            {
                DateTime validateDate;
                string[] formats = new string[] { "dd/MM/yyyy", "yyyy-MM-dd" };
                if (value == null||DateTime.TryParseExact(value.ToString(),formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out validateDate))
                {
                    return true;
                }
    
                return false;
            }
    
        }

    Demo:

     

    Hope this can help you.

    Best regards,

    Sean

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, April 18, 2020 9:10 AM

All replies

  • User-1330468790 posted

    Hi jalali,

     

    You can just validate this field and allow the value to be null.

     

    More details, you can refer to below code.

    About cshtml:

    @model MVCCaseDemo.Models.POCO
    
    @{
        ViewBag.Title = "About";
    }
    <h2>@ViewBag.Title.</h2>
    <h3>@ViewBag.Message</h3>
    
    <p>Use this area to provide additional information.</p>
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
    
        <div class="form-horizontal">
            <h4>POCO</h4>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.DecisionDate, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.DecisionDate, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.DecisionDate,"",new { @class = "text-danger" })
                </div>
            </div>
    
            
    
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Create" class="btn btn-default" />
                </div>
            </div>
        </div>
    }

    POCO class:

    public class POCO
        {
            [ValidHijriDateAttribute(ErrorMessage = "The DecisionDate must be in format of yyyy - MM - dd or dd / MM / yyyy")]
            public string DecisionDate { get; set; }
        }

     Controller:


    public ActionResult Index()
    {
    return View();
    }

    [HttpGet] public ActionResult About() { return View(); } [HttpPost] public ActionResult About(POCO poco) { if (ModelState.IsValid) { return RedirectToAction("Index"); } return View(); }

    ValidHijriDateAttribute class:

    public class ValidHijriDateAttribute : ValidationAttribute
        {
            public override bool IsValid(object value)
            {
                DateTime validateDate;
                string[] formats = new string[] { "dd/MM/yyyy", "yyyy-MM-dd" };
                if (value == null||DateTime.TryParseExact(value.ToString(),formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out validateDate))
                {
                    return true;
                }
    
                return false;
            }
    
        }

    Demo:

     

    Hope this can help you.

    Best regards,

    Sean

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, April 18, 2020 9:10 AM
  • User-1042970710 posted

    Thanks!! you save my day!!

    Saturday, April 18, 2020 5:12 PM