C# MVC 不验证空字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17511437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MVC not validate empty string
提问by Kote
I have razor file where I define html form with text box for string:
我有一个 razor 文件,我在其中定义了带有字符串文本框的 html 表单:
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Product</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
The problem is, that I want this field (model.name) not to be nullable, but razor validation allows string to be empty, when I add empty string to model it gives error. Any suggestions how to validate simply this string not to be empty anymore?
问题是,我希望这个字段 (model.name) 不能为空,但是 razor 验证允许字符串为空,当我向模型添加空字符串时,它会给出错误。任何建议如何简单地验证这个字符串不再为空?
采纳答案by sohaiby
You probably need to set the DataAnnotation attribute
您可能需要设置 DataAnnotation 属性
[Required(AllowEmptyStrings = false)]
[必需(AllowEmptyStrings = false)]
on top of your property where you want to apply the validation.
Look at this question here
RequiredAttribute with AllowEmptyString=true in ASP.NET MVC 3 unobtrusive validation
在您要应用验证的属性之上。
在这里查看这个问题
RequiredAttribute with AllowEmptyString=true in ASP.NET MVC 3 unobtrusive validation
Similar problem, more or less here.
How to convert TextBoxes with null values to empty strings
类似的问题,或多或少在这里。
如何将具有空值的文本框转换为空字符串
Hopefully, you'll be able to solve your problem
希望你能解决你的问题
回答by Thousand
what does your viewmodel look like?
你的视图模型是什么样的?
You can add a DataAnnotationattribute to your Nameproperty in your viewmodel:
您可以在视图模型中DataAnnotation为您的Name属性添加一个属性:
public class MyViewModel
{
[Required(ErrorMessage="This field can not be empty.")]
public string Name { get; set; }
}
Then, in your controller you can check whether or not the model being posted is valid.
然后,在您的控制器中,您可以检查发布的模型是否有效。
public ActionResult MyAction(ViewModel model)
{
if (ModelState.IsValid)
{
//ok
}
else
{
//not ok
}
}
回答by Flowra
This is what worked for me:
Use the following line to not accept empty string
这对我有用:
使用以下行不接受空字符串
[Required (AllowEmptyStrings = false)]
and this one to not allow white space
而这个不允许留白
[RegularExpression (@".*\S+.*", ErrorMessage = "No white space allowed")]

