【问题标题】:Make regular expression field optional which is displayed as mandatory field in MVC 4使正则表达式字段可选,在 MVC 4 中显示为必填字段
【发布时间】:2013-01-17 20:43:20
【问题描述】:

我正在研究 ASP.NET MVC 4。我在模型中使用数据注释进行验证。

有一个字段名称 Mobile 并使用正则表达式进行验证,如下所示。

[RegularExpression(@"[0-9]{10}", ErrorMessage = "Mobile Number is Not Valid")]
public string Mobile { get; set; }

根据申请要求,上述字段不是强制性的,但如果用户插入手机号码,则需要验证手机号码。

我的问题是,当我提交表单时,它显示“需要移动字段”。但是移动字段没有用[Required] 属性装饰。那么它是如何根据需要显示的呢?

可能是什么原因? 如何解决?

【问题讨论】:

  • 是否允许数据库中的移动字段为空?,如果您尝试将值存储到数据库中并且字段不允许为空,系统会抛出相同的错误。
  • 是 数据库中的移动字段允许为空。

标签: regex asp.net-mvc-4 data-annotations


【解决方案1】:

在您的项目中,有一个文件夹“views”,您可能在其中使用所需的控件创建了视图。 应该是这样的:

@Html.LabelFor(m => m.Mobile)<br />
@Html.TextBoxFor(m => m.Mobile)<br /> 

为了使正则表达式工作。 如果你已经这样做了,另一个问题可能是你的模型。 在您的视图顶部,您应该通过以下方式添加您的模型:

@model yourModelName

【讨论】:

  • 他要求使该字段仅验证输入,但仍将其保留为可选。
【解决方案2】:

由于您没有在控制器中发布任何代码,Index 被假定为控制器的操作,MyModel 被假定为模型。

在您的控制器中尝试以下代码:

 public ActionResult Index(MyModel model)
    {
       //This will check if `Mobile` is empty and remove the Mobile from validation if the field is empty
       if (collection.Get("Mobile") == "")  //Mobile is the name of the Mobile number field in view
       {
            ModelState.Remove("Mobile");
       }
       if(ModelState.IsValid){
       //do something
       }
       else{
             return View(model);
       }
    }

希望对你有帮助

【讨论】:

    【解决方案3】:

    您可以使用以下简单的 jQuery 轻松完成。

    //Remove Required field validation on pin and mobile number
        $(document).ready(function () {
            $("#Mobile").removeAttr("data-val");
        });
    

    请尝试让我们知道这是否适合您。

    谢谢

    【讨论】:

    • 这种方法似乎对我没有任何作用。空字段仍会触发正则表达式验证。似乎正则表达式验证带有required 验证。有没有办法阻止这个看起来不像黑客的问题?
    猜你喜欢
    • 2011-12-18
    • 1970-01-01
    • 1970-01-01
    • 2012-04-03
    • 1970-01-01
    • 2020-02-27
    • 1970-01-01
    • 1970-01-01
    • 2014-01-21
    相关资源
    最近更新 更多