简体   繁体   English

文本框验证根据下拉值起作用

[英]Textbox Validation Works according to dropdown value

I have a dropdown in which 3 options are available: 我有一个下拉菜单,其中有3个可用选项:

  • '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 这是我在View模型中的验证代码

[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) 您可以在post方法中进行此操作(如果需要)

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. 在更改事件上使用jQuery,如果select的值为“ Other”,则将必需的属性添加到注释框。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM