Asp.net mvc 3 如何验证一个字段与另一个字段的关联';ASP.NETMVC3中的s值
我有两个字段,比如电话号码和手机号码。比如说Asp.net mvc 3 如何验证一个字段与另一个字段的关联';ASP.NETMVC3中的s值,asp.net-mvc-3,Asp.net Mvc 3,我有两个字段,比如电话号码和手机号码。比如说 [Required] public string Phone { get; set; } [Required] public string Mobile{ get; set; } 但用户可以在其中任何一个中输入数据。一个是强制性的。如何处理它们,即当用户在另一个字段中输入数据时,如何禁用一个字段所需的字段验证程序,反之亦然。在哪种情况下,我必须用javascript处理它,我需要为此添加哪些脚本。任何人都可以帮助找
[Required]
public string Phone { get; set; }
[Required]
public string Mobile{ get; set; }
但用户可以在其中任何一个中输入数据。一个是强制性的。如何处理它们,即当用户在另一个字段中输入数据时,如何禁用一个字段所需的字段验证程序,反之亦然。在哪种情况下,我必须用javascript处理它,我需要为此添加哪些脚本。任何人都可以帮助找到解决方案…一种可能性是编写自定义验证属性:
public class RequiredIfOtherFieldIsNullAttribute : ValidationAttribute, IClientValidatable
{
private readonly string _otherProperty;
public RequiredIfOtherFieldIsNullAttribute(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,
"Unknown property {0}",
new[] { _otherProperty }
));
}
var otherPropertyValue = property.GetValue(validationContext.ObjectInstance, null);
if (otherPropertyValue == null || otherPropertyValue as string == string.Empty)
{
if (value == null || value as string == string.Empty)
{
return new ValidationResult(string.Format(
CultureInfo.CurrentCulture,
FormatErrorMessage(validationContext.DisplayName),
new[] { _otherProperty }
));
}
}
return null;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "requiredif",
};
rule.ValidationParameters.Add("other", _otherProperty);
yield return rule;
}
}
然后你可以有一个控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel());
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
}
最后是一个视图,您将在其中注册一个适配器,以连接此自定义规则的客户端验证:
@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(
'requiredif', ['other'], function (options) {
var getModelPrefix = function (fieldName) {
return fieldName.substr(0, fieldName.lastIndexOf('.') + 1);
}
var appendModelPrefix = function (value, prefix) {
if (value.indexOf('*.') === 0) {
value = value.replace('*.', prefix);
}
return value;
}
var prefix = getModelPrefix(options.element.name),
other = options.params.other,
fullOtherName = appendModelPrefix(other, prefix),
element = $(options.form).find(':input[name="' + fullOtherName + '"]')[0];
options.rules['requiredif'] = element;
if (options.message) {
options.messages['requiredif'] = options.message;
}
}
);
jQuery.validator.addMethod('requiredif', function (value, element, params) {
var otherValue = $(params).val();
if (otherValue != null && otherValue != '') {
return true;
}
return value != null && value != '';
}, '');
</script>
@using (Html.BeginForm())
{
<div>
@Html.LabelFor(x => x.Phone)
@Html.EditorFor(x => x.Phone)
@Html.ValidationMessageFor(x => x.Phone)
</div>
<div>
@Html.LabelFor(x => x.Mobile)
@Html.EditorFor(x => x.Mobile)
@Html.ValidationMessageFor(x => x.Mobile)
</div>
<button type="submit">OK</button>
}
@model MyViewModel
jQuery.validator.unobtrusive.adapters.add(
'requiredif',['other'],函数(选项){
var getModelPrefix=函数(字段名){
返回fieldName.substr(0,fieldName.lastIndexOf('.')+1);
}
var appendModelPrefix=函数(值,前缀){
if(value.indexOf('*.')==0){
value=value.replace(“*”,前缀);
}
返回值;
}
var prefix=getModelPrefix(options.element.name),
其他=options.params.other,
fullOtherName=appendModelPrefix(其他,前缀),
element=$(options.form).find(':input[name=“'+fullOtherName+'”)[0];
options.rules['requiredif']=元素;
if(options.message){
options.messages['requiredif']=options.message;
}
}
);
jQuery.validator.addMethod('requiredif',函数(值、元素、参数){
var otherValue=$(params.val();
if(otherValue!=null&&otherValue!=''){
返回true;
}
返回值!=null&&value!='';
}, '');
@使用(Html.BeginForm())
{
@LabelFor(x=>x.Phone)
@EditorFor(x=>x.Phone)
@Html.ValidationMessageFor(x=>x.Phone)
@LabelFor(x=>x.Mobile)
@EditorFor(x=>x.Mobile)
@Html.ValidationMessageFor(x=>x.Mobile)
好啊
}
对于我们日常生活中遇到的验证规则这样极其简单的事情来说,这是非常糟糕的事情。我不知道ASP.NET MVC的设计者在决定选择声明式方法而不是命令式方法进行验证时是怎么想的
无论如何,这就是为什么我使用数据注释而不是数据注释来对模型执行验证。实现这种简单的验证场景应该是以一种简单的方式实现的。我知道这个问题并不那么热门,因为它是在相对较长的时间之前提出的,不过我将与大家分享一个稍微不同的解决这类问题的想法。我决定实现一种机制,该机制提供条件属性,根据逻辑表达式中定义的其他属性值和它们之间的关系来计算验证结果 您的问题可以通过使用以下注释来定义和自动解决:
[RequiredIf("Mobile == null",
ErrorMessage = "At least email or phone should be provided.")]
public string Phone{ get; set; }
[RequiredIf("Phone == null",
ErrorMessage = "At least email or phone should be provided.")]
public string Mobile { get; set; }
如果您觉得它对您的目的有用,请参阅有关ExpressiveAnnotations库的更多信息。客户端验证也支持开箱即用。由于没有其他人建议,我将告诉您我们使用的另一种方法 如果您创建一个自定义数据类型的notmapped字段(在我的示例中,是一对gps点),您可以将验证器放在该字段上,甚至不需要使用反射来获取所有值
[NotMapped]
[DCGps]
public GPS EntryPoint
{
get
{
return new GPS(EntryPointLat, EntryPointLon);
}
}
还有这个班,一个标准的接受者/接受者
public class GPS
{
public decimal? lat { get; set; }
public decimal? lon { get; set; }
public GPS(decimal? lat, decimal? lon)
{
this.lat = lat;
this.lon = lon;
}
}
现在是验证器:
public class DCGps : DCValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (!(value is GPS)) {
return new ValidationResult("DCGps: This annotation only works with fields with the data type GPS.");
}
//value stored in the field.
//these come through as zero or emptry string. Normalize to ""
string lonValue = ((GPS)value).lonstring == "0" ? "" : ((GPS)value).lonstring;
string latValue = ((GPS)value).latstring == "0" ? "" : ((GPS)value).latstring;
//place validation code here. You have access to both values.
//If you have a ton of values to validate, you can do them all at once this way.
}
}
根据您的建议,我设置了FluentValidation。我试图解决的问题与这个问题相同,FV中的When()验证器解决了这个问题。不过,我的问题是,“When()”没有客户端验证。我对jQueryValidationATM不是很熟悉,但是为它创建客户端验证涉及很多吗?我假设它有点类似于你的答案,是吗?可以从
RequiredAttribute
继承来利用内置的错误消息。这个库很棒!我不能用这个包裹。如何使用??请。帮帮我。@lazycoder:你介意建议一下你需要什么帮助吗?
public class DCGps : DCValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (!(value is GPS)) {
return new ValidationResult("DCGps: This annotation only works with fields with the data type GPS.");
}
//value stored in the field.
//these come through as zero or emptry string. Normalize to ""
string lonValue = ((GPS)value).lonstring == "0" ? "" : ((GPS)value).lonstring;
string latValue = ((GPS)value).latstring == "0" ? "" : ((GPS)value).latstring;
//place validation code here. You have access to both values.
//If you have a ton of values to validate, you can do them all at once this way.
}
}