我正在寻找一种检查表单中两个文本框的方法,以确保至少填充其中一个文本框。仅当两个文本框都为空时,验证才会失败。使用Unobtrusive JScript和MVC3表单验证是否有一种简单的方法可以做到这一点? 感谢
答案 0 :(得分:3)
您可以实现类似answer by Darin Dimitrov之类的内容。
它解释了如何制作自己的自定义验证器(在客户端和服务器端)。它将使用MVC3验证和JQuery不显眼的验证。您可以检查是否满足条件(选中一个或多个复选框)并根据该条件进行验证。
答案 1 :(得分:0)
Javascript你可以用Jquery
这样做$(document).ready(function(){
var inp = $("#txt").val();
var inp2 = $("#txt2").val();
if(jQuery.trim(inp).length < 0 && jQuery.trim(inp2).length < 0)
{
//show your message.
}
})
答案 2 :(得分:0)
您可以查看下面提到的文章中解释的条件验证
http://blogs.msdn.com/b/simonince/archive/2010/06/04/conditional-validation-in-mvc.aspx
你可以在两个文本框中加上 [RequiredIf] 属性,并检查textBox1是否为空,然后需要textbox2,反之亦然。
答案 3 :(得分:0)
试试这个。它有所有的信息。希望它有所帮助:
http://derans.blogspot.com/2011/05/contact-form-revisited-with-aspnet-mvc.html
答案 4 :(得分:0)
尝试nuget包万无一失的验证。它包括[Requiredif]和[Requiredifnot] http://foolproof.codeplex.com/
答案 5 :(得分:0)
这是我的版本的AtLeastOneRequired验证器,支持DisplayAttribute:
[AttributeUsage(AttributeTargets.Property)]
public class AtLeastOneRequiredAttribute : ValidationAttribute
{
private readonly string[] _members;
public AtLeastOneRequiredAttribute(params string[] members)
{
_members = members;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (_members == null || _members.Length < 1)
return null;
var displayNames = new List<string>();
foreach (var member in _members)
{
var propertyInfo = validationContext.ObjectType.GetProperty(member);
if (propertyInfo == null)
throw new InternalErrorException("Property '{0}' cannot be found in '{1}'", member, validationContext.ObjectType);
var propertyValue = propertyInfo.GetValue(validationContext.ObjectInstance);
var stringValue = propertyValue as string;
if (stringValue != null && stringValue.Trim().Length != 0)
return ValidationResult.Success;
var displayAttribute = propertyInfo.GetCustomAttribute<DisplayAttribute>();
displayNames.Add(displayAttribute != null ? displayAttribute.Name : member);
}
return new ValidationResult(FormatErrorMessage(String.Join(", ", displayNames)));
}
}
非常简单的模型:
public class FeedbackPostModel
{
[Display(Name = "Phone")]
[AtLeastOneRequired("SenderPhone", "SenderEmail", ErrorMessageResourceName = "ValidationAtLeastOnRequired", ErrorMessageResourceType = typeof(Strings))]
[StringLength(256, ErrorMessageResourceName = "ValidationFieldStringLengthMax", ErrorMessageResourceType = typeof(Strings))]
[Phone(ErrorMessageResourceName = "ValidationFieldPhoneFormat", ErrorMessageResourceType = typeof(Strings))]
public string SenderPhone { get; set; }
[Display(Name = "Email")]
[StringLength(256, ErrorMessageResourceName = "ValidationFieldStringLengthMax", ErrorMessageResourceType = typeof(Strings))]
[EmailAddress(ErrorMessageResourceName = "ValidationFieldEmailAddress", ErrorMessageResourceType = typeof(Strings))]
public string SenderEmail { get; set; }
}