2011-08-08 14 views
19

Burada basit sorun (bence).Veri ek açıklamaları kullanılarak bir modelin boolean değerinin true olmasını zorunlu kılma

Kullanıcının şartlar ve koşulları kabul etmesi gereken altta bir onay kutusu bulunan bir form var. Kullanıcı kutuyu işaretlemiyorsa, diğer form hatalarıyla birlikte doğrulama özetimde görüntülenecek bir hata mesajı istiyorum.

[Required] 
[Range(1, 1, ErrorMessage = "You must agree to the Terms and Conditions")] 
public bool AgreeTerms { get; set; } 

Ama bu işe yaramadı:

benim bakış modeline bu ekledi.

Veri ek açıklamaları ile bir değeri doğrulamak için zorlamanın kolay bir yolu var mı?

+0

Özel ek açıklamalar yazmak çok kolay, bu seçeneği düşündünüz mü? – asawyer

+0

Bir boole için değil, çok benzer (ve özel hata iletilerine izin verir): http://rical.blogspot.com/2012/03/server-side-custom-annotation.html – pkr298

cevap

24
using System.Collections.Generic; 
using System.ComponentModel.DataAnnotations; 
using System.Threading.Tasks; 
using System.Web.Mvc; 

namespace Checked.Entitites 
{ 
    public class BooleanRequiredAttribute : ValidationAttribute, IClientValidatable 
    { 
     public override bool IsValid(object value) 
     { 
      return value != null && (bool)value == true; 
     } 

     public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) 
     { 
      //return new ModelClientValidationRule[] { new ModelClientValidationRule() { ValidationType = "booleanrequired", ErrorMessage = this.ErrorMessage } }; 
      yield return new ModelClientValidationRule() 
      { 
       ValidationType = "booleanrequired", 
       ErrorMessage = this.ErrorMessageString 
      }; 
     } 
    } 
} 
6

Zaten belirtilmiş olan bir özel doğrulama özniteliği yazabilirsiniz. İstemci tarafı doğrulaması yapıyorsanız göze batmayan doğrulama işlevini etkinleştirmek için özel javascript yazmanız gerekir. Örneğin. jQuery kullanıyorsanız: her zaman doğru olarak ayarlanmış olan model üzerinde bir özellik olması

// extend jquery unobtrusive validation 
(function ($) { 

    // add the validator for the boolean attribute 
    $.validator.addMethod(
    "booleanrequired", 
    function (value, element, params) { 

     // value: the value entered into the input 
     // element: the element being validated 
     // params: the parameters specified in the unobtrusive adapter 

     // do your validation here an return true or false 

    }); 

    // you then need to hook the custom validation attribute into the MS unobtrusive validators 
    $.validator.unobtrusive.adapters.add(
    "booleanrequired", // adapter name 
    ["booleanrequired"], // the names for the properties on the object that will be passed to the validator method 
    function(options) { 

     // set the properties for the validator method 
     options.rules["booleanRequired"] = options.params; 

     // set the message to output if validation fails 
     options.messages["booleanRequired] = options.message; 

    }); 

} (jQuery)); 

Başka yolu (a kesmek bir parçasıdır ve ben bunu sevmiyorum), o zaman kullanmak * AgreeTerms * özniteliğinizin değerini karşılaştırmak için numaralı KarşılaştırÜz. Basit evet ama sevmiyorum :)

+0

Anahtarlar büyük/küçük harfe duyarlıdır: booleanrequired booleanRequired –

İlgili konular