我寫過一個屬性,但我沒有寫過驗證屬性。我對這一切如何協同工作感到非常困惑。我已閱讀了大部分在線教程,介紹如何完成此任務。但我留下了幾個問題來思考。不明白寫作自己的驗證屬性的機制
請記住,我正在嘗試編寫一個requiredIf屬性,如果設置了某個Jquery變量,它將只調用遠程函數...偶然是從視圖狀態拉出的變量...我想我可以成爲我的觀點模型的一部分。但我離題了
1)C#代碼有點混亂。我知道我的屬性應該分別擴展ValidationAttribute,IClientValidatable類和接口。但是我對每個過濾方法應該做什麼感到困惑?我正在嘗試編寫一個必需的,如何覆蓋這些方法來幫助我實現這個目標?
2)如果變量不存在,我只是不希望遠程函數試圖驗證該字段。我不希望任何消息在我的表單上彈出。許多教程似乎都圍繞着這個。
3)我很困惑我需要做什麼與jquery將此功能添加到視圖中...我需要添加到JQuery才能讓這個東西工作......它看起來像一個很多額外的編碼,當我可以簡單地輸入一個jquery函數來完成同樣的事情時,只用相同的少量編碼......我知道它也增加了服務器端驗證,這是很好的。但仍...
以下是我對這個公式我jQuery的身邊...
(function ($) {
$validator.unobtrusive.adapters.addSingleVal("requiredifattribute", "Dependent");
$validator.addMethod("requiredifattribute", function (value, element, params) {
if (!this.optional(element)) {
var otherProp = $('#' + params)
return (otherProp.val() != value);
}
return true;
})
}(jQuery));
這裏是我的屬性(基本上是碳複製出一個所需要的,如果教程..我知道,我需要更多的自定義,但一旦我得到的東西每一塊做一個更好的主意,我會做到這一點...
[AttributeUsage(AttributeTargets.Property)]
public class RequiredIfAttribute : ValidationAttribute, IClientValidatable {
private const string errorMessage = "The {0} is required.";
//public string
private RequiredAttribute innerAttribute = new RequiredAttribute();
public string DependentProperty { get; set; }
public object TargetValue { get; set; }
public RequiredIfAttribute(string dependentProperty, object targetValue){
this.DependentProperty = dependentProperty;
this.TargetValue = targetValue;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
var field = validationContext.ObjectInstance.GetType().GetProperty(DependentProperty);
if (field != null) {
var dependentValue = field.GetValue(validationContext.ObjectInstance, null);
if ((dependentValue == null && TargetValue == null) || (dependentValue.Equals(TargetValue))) {
if (!innerAttribute.IsValid(value))
return new ValidationResult(ErrorMessage);
}
}
return ValidationResult.Success;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) {
ModelClientValidationRule modelClientValidationRule = new ModelClientValidationRule {
ErrorMessage = FormatErrorMessage(metadata.DisplayName),
ValidationType = "requiredifattribute"
};
modelClientValidationRule.ValidationParameters.Add("dependent", DependentProperty);
yield return modelClientValidationRule;
}
}
更新:我有什麼根本不工作
這是在我的模型的屬性是如何anotated上述屬性
[RequiredIf("isFlagSet", true)]
[Remote("ValidateHosFin", "EditEncounter", AdditionalFields = "hospitalFin, encflag", ErrorMessage = "Got Damn this is complex!")]
[MinLength(6)]
public string HostpitalFinNumber { get; set; }
,我試圖加鍵設置像這樣此驗證在我看來,價值...
ViewData["ADDENCOREDITTEMP"] = encflag;
if (encflag == "AddEnc"){
isFlagSet = true;
}
我將其嵌入到我的網頁是這樣的...
@Html.Hidden("isFlagSet", isFlagSet, new { id = "isFlagSet"})
我不能讓我的表單提交...誰說他只是嘗試這樣做,得到它的工作的人,你能不能發佈代碼?
究竟是什麼問題? – Necros
如果你想知道數據註解模型驗證工作如何查看源代碼,沒有太多的文檔可用 – VJAI
嗯,我想我嘗試寫我自己的,到目前爲止我還沒有得到它的工作。我顯然錯過了一些更好的觀點,我正在嘗試更好地掌握做什麼。我知道我想做什麼,但我很難從A到B這麼說。 – SoftwareSavant