ساخت یک ValidationAttribute
با سلام یه نمونه درست کردم
public class CustomVaildation : ValidationAttribute {
public string CodeMeli { set; get; }
public override bool IsValid(object value)
{
if (value == null) return false;
if (value.ToString().Length == 10) return true;
else
return false;
}
}
public class VM {
[Required(ErrorMessage = "مقدار الزامی است")]
[CustomVaildation(ErrorMessage = "کد ملی 10 رقم نیست")]
public string CodeMeli { get; set; }
}
@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "signupform" })){
@Html.ValidationSummary(true)
<div class="editor-label">
@Html.LabelFor(model => model.CodeMeli)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.CodeMeli)
@Html.ValidationMessageFor(model => model.CodeMeli)
</div>
اما کار نیمکنه.
فقط مشکل روی این کاستوم است
نقل قول: ساخت یک ValidationAttribute
اگر صرفا فقط برای طول رشته میخواید یک Custom Attribute تعریف کنید ، بهتره که از MaxLength و MinLength استفاده کنید .
اگر برای کد ملی میخواید استفاده کنید ، میتونید از این استفاده کنید : http://iranganj.com/post/10587/%D8%A...8%AF%D8%B1-mvc
و کدی که فرستادید صحیحش :
public class IdentityCodeValidator : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
string identityCode = value.ToString();
if (identityCode.Length == 10)
return ValidationResult.Success;
else
return new ValidationResult("Please Enter a Valid Identity Code.");
}
return new ValidationResult("" + validationContext.DisplayName + " is required");
}
}
آموزش استفاده از Custom Attribute ها : http://www.c-sharpcorner.com/UploadF...ion-attribute/
نقل قول: ساخت یک ValidationAttribute
این مطلب
http://www.c-sharpcorner.com/UploadF...ion-attribute/
من می خوام بدون کلیک روی submit این تشخیص داده بشه.
یعنی تضخیص به صورت ajax باشه
نقل قول: ساخت یک ValidationAttribute
اصلاحالا به این چیزی که شما میخاین میگن dynamic validation . شما باید از remote استفاده کنید وقتی به طور ایجکسی این کار رو میخاین انجام بدین. به طور مثال شما از این نمونه میتونین استفاده کنید
public class AddressViewChannelModel {
[Display(Name = "CountryID")]
public Guid? countryID { get; set; }
[Required]
[Remote("ValidateZipCode", "Address", AdditionalFields = "countryID")]
[Display(Name = "Zip")]
public string zip { get; set; }
}
public class AddressController : Controller
{
public JsonResult ValidateZipCode(string zip, string countryID)
{
ValidationRequest request = new ValidationRequest();
request.CountryID = Guid.Parse(countryID);
request.Zip = zip;
ValidationResponse response = new ValidationResponse();
response = _addressApi.ZipValidation(request);
if (response.IsSuccessful == false)
{ return Json("Not a valid zip code for your chosen country!"), JsonRequestBehavior.AllowGet); }
else { return Json(true, JsonRequestBehavior.AllowGet); }
}
}