gpt4 book ai didi

jquery - 客户端条件验证 RequiredIf 属性

转载 作者:行者123 更新时间:2023-11-28 15:29:04 24 4
gpt4 key购买 nike

我有一个带有两个单选按钮的 asp.net MVC 4 View 。在页面加载时, View 的一部分使用 css 隐藏。在 View 本身上,当用户选择一个单选按钮时,一旦隐藏部分并显示其他部分,当单击其他单选按钮时,显示其他部分。我想根据选中的复选框执行条件验证。我已经创建了 RequriredIf 属性,但它仅适用于服务器端。代码是:

 public class RequiredIfAttribute : ValidationAttribute
{
private String PropertyName { get; set; }
private String ErrorMessage { get; set; }
private Object DesiredValue { get; set; }

public RequiredIfAttribute(String propertyName, Object desiredvalue, String errormessage)
{
this.PropertyName = propertyName;
this.DesiredValue = desiredvalue;
this.ErrorMessage = errormessage;
}

protected override ValidationResult IsValid(object value, ValidationContext context)
{
Object instance = context.ObjectInstance;
Type type = instance.GetType();
Object proprtyvalue = type.GetProperty(PropertyName).GetValue(instance, null);
if (proprtyvalue.ToString() == DesiredValue.ToString() && value == null)
{
return new ValidationResult(ErrorMessage);
}
return ValidationResult.Success;
}
}

下面是我如何使用这个属性:

 [RequiredIf("LocationType", LocationTypeEnum.BuildingOffice, "Please enter building number")]
public string BuildingNumberName
{
get { return _BuildingNumberName; }
set { _BuildingNumberName = value; }
}

[RequiredIf("LocationType", LocationTypeEnum.BuildingOffice, "Please enter floor number")]
private string _Floor = string.Empty;

public string Floor
{
get { return _Floor; }
set { _Floor = value; }
}

private string _ApartmentOfficeNumber = string.Empty;

[RequiredIf("LocationType", LocationTypeEnum.BuildingOffice, "Please enter appartment/office number")]
public string ApartmentOfficeNumber
{
get { return _ApartmentOfficeNumber; }
set { _ApartmentOfficeNumber = value; }
}

private string _HouseNumber = string.Empty;

[RequiredIf("LocationType", LocationTypeEnum.VillaHouse, "Please enter house number")]
public string HouseNumber
{
get { return _HouseNumber; }
set { _HouseNumber = value; }
}

这有一些缺点:

1) 它确实会回发,因此用户必须等待回发并修复错误。2) 回发后,默认部分被隐藏(使用 css)。

我想使用客户端来实现。我需要做什么?

最佳答案

我相信您需要添加到您的 web.config 文件以启用客户端验证。

<configuration>
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
</configuration>

关于jquery - 客户端条件验证 RequiredIf 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23359681/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com