Share via


asp.net mvc dataAnnotations enforcing a value is true?

Question

Tuesday, April 27, 2010 2:36 PM

Using data annotations for asp.net MVC, I can enforce range, regular expressions, required, stringlength, etc.. However, I have boolean property "SignedDocument" that I want to enforce its set to true? Is this possible in data annotation?

Example:

 [Required(ErrorMessage = "Phone is Required ")]
        [RegularExpression(@"^(\()?(787|939)(\)|-)?([0-9]{3})(-)?([0-9]{4}|[0-9]{4})$", ErrorMessage = "Phone has an Invalid format")]
[Required(ErrorMessage = "Phone is Required ")]
        public string Phone { get; set; }

// document must be signed in order to add (!= false) 
public boolean SignedDocument{ get; set; }

 

All replies (5)

Tuesday, April 27, 2010 2:56 PM ✅Answered

 [Required]

        [Range(minimum:1, maximum:1)]

        public bool agree { get; set; }

You could add in a range validator 

 [Required]
 [Range(minimum:1, maximum:1)]
 public bool agree { get; set; }

Tuesday, April 27, 2010 7:16 PM ✅Answered

The easiest thing to do is to make your own attribute for this:

public sealed class MustBeTrueAttribute : ValidationAttribute {
    public override bool IsValid(object value) {
        return Object.Equals(value, true);
    }
}

If you also need client-side validation, see the tutorial at http://bradwilson.typepad.com/blog/2010/01/remote-validation-with-aspnet-mvc-2.html for how to write your own client-side validator.


Thursday, April 29, 2010 12:22 PM ✅Answered

Also see my complete sample downloads at http://code.msdn.microsoft.com/aspnetmvcsamples/Release/ProjectReleases.aspx?ReleaseId=3038

 


Tuesday, April 27, 2010 2:47 PM

 simply have the EmailAttribute validator return true if the value is null or empty.

Think about it:

  • If the e-mail address is required, then there will also be a [Required] validator and a null/empty e-mail address will generate a validation error anyway;

  • If the e-mail address is optional, a null/empty value should be considered valid.

No need to solve the complex problem of intercepting validators when you can just design the individual validators.


Tuesday, April 27, 2010 2:54 PM

 Maybe I misread your post, how would an email attribute validator enforce a boolean property called "SignedDocument" to be true (not false)?