我有一个标准的地址表单,其中包含许多字段。例如
问题是只有当“country”设置为USA时,“state”字段才是必填字段。如果国家设置为其他任何东西,则不应该要求它。我可以在控制器中处理它,但我想在客户端不显眼地做它。有什么建议?
刚刚为您的要求写了一个快速演示。
// model
public class Address
{
public int Id { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
[Required]
public string Country { get; set; }
[RequiredIfCountryIsUSA]
public string State { get; set; }
public string PostCode { get; set; }
}
// Validation Attribute
public class RequiredIfCountryIsUSA : ValidationAttribute, IClientValidatable
{
public RequiredIfCountryIsUSA()
{
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var countryPropertyInfo = validationContext.ObjectInstance.GetType().GetProperty("Country");
var countryValue = countryPropertyInfo.GetValue(validationContext.ObjectInstance, null).ToString();
if (countryValue == "USA" && (value == null || string.IsNullOrEmpty(value.ToString().Trim())))
{
return new ValidationResult("State is required when Country is USA");
}
return ValidationResult.Success;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule();
rule.ErrorMessage = "State is required when country is USA";
rule.ValidationParameters.Add("country", "USA");
rule.ValidationType = "iscountryusa";
yield return rule;
}
}
客户端javascript
(function ($) {
$.validator.addMethod("iscountryusa", function (state, element, country) {
var country = $('#Country').val();
if (country == 'USA' && state == '') {
return false;
}
return true;
});
$.validator.unobtrusive.adapters.addSingleVal("iscountryusa", "country");
} (jQuery));
看看MVC Foolproof。 http://foolproof.codeplex.com/。您可以将包装到您的解决方案中。
它具有这些可能对你有帮助的属性;
[RequiredIf]
[RequiredIfNot]
[RequiredIfTrue]
[RequiredIfFalse]
[RequiredIfEmpty]
[RequiredIfNotEmpty]
[RequiredIfRegExMatch]
[RequiredIfNotRegExMatch]
我使用js文件使它变得简单。我创建了名为“CountryValidate.js”的Js文件,并像这样编写
var list = ["India", "Australia", "Pakisthan"];
$(document).ready(function(){
debugger
$("#Country").keyup(function () {
debugger
for (var i = 0; i < list.length; i++) {
if ($("#Country").val() !== list[i]) {
$("#error").show();
}
else {
$("#error").hide();
break;
}
}
});
});
并在视图中添加了一些语句(Student.cshtml)我为Country Name Text Box添加了这个属性
<span class="validation has-error text-danger" id="error" hidden>Invalid Country Name</span>
更改我使文本框显示验证消息。