简体   繁体   中英

Textbox Validation Works according to dropdown value

I have a dropdown in which 3 options are available:

  • 'Cancelled'
  • 'Postponed'
  • 'Other'

I want that if the user selects the 'Other' option then the Comment textbox is mandatory, otherwise the Comment textbox is not mandatory,

Here is my validation code in the View Model

[Required(ErrorMessage="Please Enter Comment")]
public string Comment { get; set; }

and here is my Dropdown and validation code in view

@Html.DropDownList("Reason", new List<SelectListItem>()
{
    new SelectListItem() { Text= "Event Cancelled", Value = "Cancelled" },
    new SelectListItem() { Text= "Event  PostPoned", Value = "PostPoned" },
    new SelectListItem() { Text= "Other", Value = "Other" }    
}, "--Select Cancellation Reason --", new { @class = "form-control"})
@Html.ValidationMessageFor(model => model.Reason, "", new { @class = "text-danger" })

How do I make the comment mandatory only when other is selected?

There is a scope of doing this in your post method(If you want)

Public ActionResult AssumeThisAsYourPostMethod(YourModel modelObject)
{
  if(modelObject.Reason=="Other" && String.IsNullOrEmpty(modelObject.Comment) )
  {
    ModelState.AddModelError("Comment","Your Validation Message");
    return View("YourViewName");
  }
}

Use jQuery on change event and if the value of the select is 'Other' then add required property to comment box.

$("body").on('change', "#Reason", function () {
   var Reason= $(this).val().trim() ;
   if (Reason == 'Other')
    {
     $("input[name = Comment]").prop('required',true);
    } 
   });

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