javascript mvc3 验证输入“不等于”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5736710/
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
mvc3 validate input 'not-equal-to'
提问by BZink
My forms have inputs with default helper text that guides the user on what to enter (rather than using labels). This makes validation tricky because the input value is never null.
我的表单输入带有默认帮助文本,可指导用户输入内容(而不是使用标签)。这使得验证变得棘手,因为输入值永远不会为空。
How can I extend unobtrusive validation to handle this? The form shouldn't be valid if the Name input is equal to "Please enter your name..."
如何扩展不显眼的验证来处理这个问题?如果名称输入等于“请输入您的姓名...”,则该表单无效
I started reading Brad Wilson's blog poston validation adapters, but I'm not sure if this is the right way to go? I need to be able to validate against different default values depending on the field.
我开始阅读Brad Wilson关于验证适配器的博客文章,但我不确定这是否正确?我需要能够根据字段对不同的默认值进行验证。
Thanks
谢谢
采纳答案by Daniel A. White
Yes thats the right way to go. You should implement your own atribute and implement IClientValidatable
.
是的,这是正确的方法。您应该实现自己的属性并实现IClientValidatable
.
You could also have a required boolean value set initially to false
as a hidden form field. When the user changes the textbox, set it to true.
您还可以将所需的布尔值最初设置false
为隐藏表单字段。当用户更改文本框时,将其设置为 true。
回答by Darin Dimitrov
Here's a sample illustrating how you could proceed to implement a custom validation attribute:
这是一个示例,说明如何继续实现自定义验证属性:
public class NotEqualAttribute : ValidationAttribute, IClientValidatable
{
public string OtherProperty { get; private set; }
public NotEqualAttribute(string otherProperty)
{
OtherProperty = otherProperty;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var property = validationContext.ObjectType.GetProperty(OtherProperty);
if (property == null)
{
return new ValidationResult(
string.Format(
CultureInfo.CurrentCulture,
"{0} is unknown property",
OtherProperty
)
);
}
var otherValue = property.GetValue(validationContext.ObjectInstance, null);
if (object.Equals(value, otherValue))
{
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
return null;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = ErrorMessage,
ValidationType = "notequalto",
};
rule.ValidationParameters["other"] = OtherProperty;
yield return rule;
}
}
and then on the model:
然后在模型上:
public class MyViewModel
{
public string Prop1 { get; set; }
[NotEqual("Prop1", ErrorMessage = "should be different than Prop1")]
public string Prop2 { get; set; }
}
controller:
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel
{
Prop1 = "foo",
Prop2 = "foo"
});
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
}
and view:
并查看:
@model MyViewModel
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script type="text/javascript">
jQuery.validator.unobtrusive.adapters.add(
'notequalto', ['other'], function (options) {
options.rules['notEqualTo'] = '#' + options.params.other;
if (options.message) {
options.messages['notEqualTo'] = options.message;
}
});
jQuery.validator.addMethod('notEqualTo', function(value, element, param) {
return this.optional(element) || value != $(param).val();
}, '');
</script>
@using (Html.BeginForm())
{
<div>
@Html.LabelFor(x => x.Prop1)
@Html.EditorFor(x => x.Prop1)
@Html.ValidationMessageFor(x => x.Prop1)
</div>
<div>
@Html.LabelFor(x => x.Prop2)
@Html.EditorFor(x => x.Prop2)
@Html.ValidationMessageFor(x => x.Prop2)
</div>
<input type="submit" value="OK" />
}
回答by jwaliszko
It took a little while since your question was asked, but if you still like data annotations, this problem can be easily solved using this library:
自从提出您的问题以来花了一些时间,但是如果您仍然喜欢数据注释,则可以使用此库轻松解决此问题:
[Required]
[AssertThat("FieldA != 'some text'")]
public string FieldA { get; set; }
Above, the field value is compared with some pre-defined text. Alternatively, you can compare fields values with each other:
上面,字段值与一些预定义的文本进行了比较。或者,您可以相互比较字段值:
[AssertThat("FieldA != FieldB")]
...and when the case of the strings being compared does not matter:
...当比较字符串的大小写无关紧要时:
[AssertThat("CompareOrdinalIgnoreCase(FieldA, FieldB) != 0")]
回答by Query
To improve a little bit of @Darin Dimitrov answer, if you want to add messages from the resources using ErrorMessageResourceName and ErrorMessageResourceType
, just add this to the to the Error message ErrorMessage = ErrorMessage ?? ErrorMessageString
为了改进@Darin Dimitrov 的回答,如果您想使用从资源中添加消息ErrorMessageResourceName and ErrorMessageResourceType
,只需将此添加到错误消息中ErrorMessage = ErrorMessage ?? ErrorMessageString
The ErrorMessageString will look for the localized version of error message that you set in the model using those parameters (ErrorMessageResourceName and ErrorMessageResourceType)
ErrorMessageString 将使用这些参数(ErrorMessageResourceName 和 ErrorMessageResourceType)查找您在模型中设置的错误消息的本地化版本
回答by Rich Whitfield
You could make your ViewModel implement IValidatableObject and when implementing the Validate method (from IValidatableObject) add some logic to check the values of the properties e.g.
您可以让您的 ViewModel 实现 IValidatableObject,并在实现 Validate 方法(来自 IValidatableObject)时添加一些逻辑来检查属性的值,例如
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
var results = new List<ValidationResult>();
if (Name == "Please enter your name...")
results.Add(new ValidationResult("You must enter a name");
...
Enter other validation here
...
return results;
}
Now, when Model.IsValid is called in your controller, this bit of logic will be ran and will return validation errors as normal.
现在,当在您的控制器中调用 Model.IsValid 时,将运行该位逻辑并将正常返回验证错误。
回答by Leons
The ideal solutions is a custom Attribute where you specify minimum and maximum lengths as well as MustNotContain="Please enter your name...".
理想的解决方案是自定义属性,您可以在其中指定最小和最大长度以及 MustNotContain="请输入您的姓名..."。