I'm looking for a way to check two textboxes in a form to make sure at least one of them is populated. The validation should fail only if both textboxes are empty. Is there an easy way to do this using Unobtrusive JScript and MVC3 form validation?
Thanks
You could implement something like this answer by Darin Dimitrov.
It explains how to make your own custom validator (on both client and server side). It will use the MVC3 validation and JQuery unobtrusive validation. You could check if the condition is met (one or more checkboxes are checked) and validate based on that.
Javascript you can do this way using Jquery
$(document).ready(function(){
var inp = $("#txt").val();
var inp2 = $("#txt2").val();
if(jQuery.trim(inp).length < 0 && jQuery.trim(inp2).length < 0)
{
//show your message.
}
})
You can look the conditional validation explained in below mentioned article
http://blogs.msdn.com/b/simonince/archive/2010/06/04/conditional-validation-in-mvc.aspx
you can put [RequiredIf] attribute on both text boxes and check if textBox1 is empty then textbox2 is required and vice versa.
Try this. It has all the info. Hope it helps:
http://derans.blogspot.com/2011/05/contact-form-revisited-with-aspnet-mvc.html
Try nuget package foolproof validation. It includes [Requiredif] and [Requiredifnot] http://foolproof.codeplex.com/
Here is mine version of AtLeastOneRequired validator with supporting DisplayAttribute:
[AttributeUsage(AttributeTargets.Property)]
public class AtLeastOneRequiredAttribute : ValidationAttribute
{
private readonly string[] _members;
public AtLeastOneRequiredAttribute(params string[] members)
{
_members = members;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (_members == null || _members.Length < 1)
return null;
var displayNames = new List<string>();
foreach (var member in _members)
{
var propertyInfo = validationContext.ObjectType.GetProperty(member);
if (propertyInfo == null)
throw new InternalErrorException("Property '{0}' cannot be found in '{1}'", member, validationContext.ObjectType);
var propertyValue = propertyInfo.GetValue(validationContext.ObjectInstance);
var stringValue = propertyValue as string;
if (stringValue != null && stringValue.Trim().Length != 0)
return ValidationResult.Success;
var displayAttribute = propertyInfo.GetCustomAttribute<DisplayAttribute>();
displayNames.Add(displayAttribute != null ? displayAttribute.Name : member);
}
return new ValidationResult(FormatErrorMessage(String.Join(", ", displayNames)));
}
}
And very simple model:
public class FeedbackPostModel
{
[Display(Name = "Phone")]
[AtLeastOneRequired("SenderPhone", "SenderEmail", ErrorMessageResourceName = "ValidationAtLeastOnRequired", ErrorMessageResourceType = typeof(Strings))]
[StringLength(256, ErrorMessageResourceName = "ValidationFieldStringLengthMax", ErrorMessageResourceType = typeof(Strings))]
[Phone(ErrorMessageResourceName = "ValidationFieldPhoneFormat", ErrorMessageResourceType = typeof(Strings))]
public string SenderPhone { get; set; }
[Display(Name = "Email")]
[StringLength(256, ErrorMessageResourceName = "ValidationFieldStringLengthMax", ErrorMessageResourceType = typeof(Strings))]
[EmailAddress(ErrorMessageResourceName = "ValidationFieldEmailAddress", ErrorMessageResourceType = typeof(Strings))]
public string SenderEmail { get; set; }
}
Related
Has anyone seen an MVC3 data annotation for Date validation that requires a single selected date to be equal to or greater than current date?
If there's already a third party add on that's cool too. I'm already using the DataAnnotationsExtensions but it doesn't offer what I'm looking for.
There doesn't seem to be any reference of this on. So, hoping someone has already solved this before I try to reinvent the wheel and write my own custom validator.
I've tried Range but that requires 2 dates and both have to be constants in string format such as [Range(typeof(DateTime), "1/1/2011", "1/1/2016")] but that doesn't help. And the DataAnnotationsExtensions Min validator only accepts int and double
Update Solved
Thanks to #BuildStarted this is what I ended up with and it works great server-side and now client side with my script
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace Web.Models.Validation {
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class DateMustBeEqualOrGreaterThanCurrentDateValidation : ValidationAttribute, IClientValidatable {
private const string DefaultErrorMessage = "Date selected {0} must be on or after today";
public DateMustBeEqualOrGreaterThanCurrentDateValidation()
: base(DefaultErrorMessage) {
}
public override string FormatErrorMessage(string name) {
return string.Format(DefaultErrorMessage, name);
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
var dateEntered = (DateTime)value;
if (dateEntered < DateTime.Today) {
var message = FormatErrorMessage(dateEntered.ToShortDateString());
return new ValidationResult(message);
}
return null;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) {
var rule = new ModelClientCustomDateValidationRule(FormatErrorMessage(metadata.DisplayName));
yield return rule;
}
}
public sealed class ModelClientCustomDateValidationRule : ModelClientValidationRule {
public ModelClientCustomDateValidationRule(string errorMessage) {
ErrorMessage = errorMessage;
ValidationType = "datemustbeequalorgreaterthancurrentdate";
}
}
}
And in my model
[Required]
[DateMustBeEqualOrGreaterThanCurrentDate]
public DateTime SomeDate { get; set; }
The client side script
/// <reference path="jquery-1.7.2.js" />
jQuery.validator.addMethod("datemustbeequalorgreaterthancurrentdate", function (value, element, param) {
var someDate = $("#SomeDate").val();
var today;
var currentDate = new Date();
var year = currentDate.getYear();
var month = currentDate.getMonth() + 1; // added +1 because javascript counts month from 0
var day = currentDate.getDate();
var hours = currentDate.getHours();
var minutes = currentDate.getMinutes();
var seconds = currentDate.getSeconds();
today = month + '/' + day + '/' + year + ' ' + hours + '.' + minutes + '.' + seconds;
if (someDate < today) {
return false;
}
return true;
});
jQuery.validator.unobtrusive.adapters.addBool("datemustbeequalorgreaterthancurrentdate");
Create a custom attribute.
public class CheckDateRangeAttribute: ValidationAttribute {
protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
DateTime dt = (DateTime)value;
if (dt >= DateTime.UtcNow) {
return ValidationResult.Success;
}
return new ValidationResult(ErrorMessage ?? "Make sure your date is >= than today");
}
}
code was written off the cuff so fix any errors :)
Use [Remote] for special validations, simple and easy:
Your model:
[Remote("ValidateDateEqualOrGreater", HttpMethod="Post",
ErrorMessage = "Date isn't equal or greater than current date.")]
public DateTime Date { get; set; }
//other properties
Your action:
[HttpPost]
public ActionResult ValidateDateEqualOrGreater(DateTime Date)
{
// validate your date here and return True if validated
if(Date >= DateTime.Now)
{
return Json(true);
}
return Json(false);
}
Simple way to accomplish this task is using CompareValidator.
The code below uses AjaxControlToolKit's CalendarExtender.
Copy the below code to your HTML directive
<asp:TextBox ID="txtCompletionDate" runat="server" CssClass="txtNormal"></asp:TextBox>
<cc1:CalendarExtender ID="CalendarExtender1" TargetControlID="txtCompletionDate"
Format="dd/MM/yyyy" runat="server">
</cc1:CalendarExtender>
<asp:RequiredFieldValidator ID="rfvCompletionDate" runat="server" ControlToValidate="txtCompletionDate"
CssClass="labelError" ErrorMessage="*"></asp:RequiredFieldValidator>
<asp:CompareValidator ID="cvDate" runat="server" ControlToCompare="hiddenbox" ErrorMessage="*"
ControlToValidate="txtCompletionDate" CssClass="labelError" ToolTip="Completion Date should be greater than or equal to Today"
Operator="GreaterThanEqual" Type="Date"></asp:CompareValidator>
<asp:TextBox ID="hiddenbox" runat="server" CssClass="hiddenbox">
</asp:TextBox>
add the below line in the CSS
.hiddenbox {display:none;}
What do I want to achieve:
To show a seperate validation message for failing minimum age check and one for maximum age check
To store the minimum and maximum age in one area as integers. Not in js/ validator... only in the model. which I hope to change to look at a config file.
For the validation to work with jquery unobtrusive and server side, and to be in one place against the model (and obv some jquery)
To be enabled using data annotations
I wanted to check against DOB as a datetime, not have the user put in there age as an int. If i did I could have used [Min] notation and [Max] notation for age. It wasn't good enough.
Why didn't I use a range notation. I wanted to fire a different validation message for each min fail and max fail. I looked into this and had no look. I'd also have to pass in the range as a datetime and its static or something so I couldn't have done DateTime.Now.AddYears(-90) for instance.
My problems
I'm a noob at MVC, JQuery validation and the whole MVC architecture!
What I've come up with works. However, as you can see there is alot repeated code, I'd like to conform to DRY.
My first hack was to pass in the value that i'm checking against into the validation message. I got around this by doing...
[MaximumAgeCheck(90,"You have to be at most {0} to apply")]
and inside the validation attribute
private readonly int _min;
private readonly string _defaultErrorMessage = "";
public MinimumAgeCheck(int min, string defaultErrorMessage)
: base(defaultErrorMessage)
{
_min = min;
_defaultErrorMessage = defaultErrorMessage.Replace("{0}", _min.ToString());
}
and I used it for instance like so..
return new ValidationResult(_defaultErrorMessage);
I know this isn't the right way to do it, and wondered what is the best way to do this?
Second hack!
I'm passing in two validation parameters which I want to be able to access in the jQuery.validator.addMethod... method.
I tried to access these parameters by doing the following... params.[thevalueiadded], params[0]... etc, I even logged out params into console.log but it never showed me all the params, only the first value as a string!
My work around was to store the javascript variables at the top and load them from the adapters.add.
I'm probabily making little sense so here is the code, that works...I warn you, it is messy!
Model property and data annotation
[Required(ErrorMessage = "Date of birth required")]
[Display(Name = "Date of Birth")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
[DataType(DataType.DateTime, ErrorMessage = "Date of birth should be in dd/mm/yyyy format")]
[MinimumAgeCheck(18,"You have to be at least {0} to apply")]
[MaximumAgeCheck(90,"You have to be at most {0} to apply")]
public DateTime? DateOfBirth { get; set; }
Minimum Age Check and Maximum age check
validation attributes
public class MinimumAgeCheck : ValidationAttribute, IClientValidatable
{
private readonly int _min;
private readonly string _defaultErrorMessage = "";
public MinimumAgeCheck(int min, string defaultErrorMessage)
: base(defaultErrorMessage)
{
_min = min;
_defaultErrorMessage = defaultErrorMessage.Replace("{0}", _min.ToString());
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
DateTime dtV = (DateTime)value;
long lTicks = DateTime.Now.Ticks - dtV.Ticks;
DateTime dtAge = new DateTime(lTicks);
if (!(dtAge.Year >= _min && dtAge.Year <= 30))
{
return new ValidationResult(_defaultErrorMessage);
}
return ValidationResult.Success;
}
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString, _min);
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
ModelClientValidationRule mcvrTwo = new ModelClientValidationRule();
mcvrTwo.ValidationType = "checkminimumage";
mcvrTwo.ErrorMessage = _defaultErrorMessage;
mcvrTwo.ValidationParameters.Add("todaysdate", DateTime.Now.ToString("dd/MM/yyyy"));
mcvrTwo.ValidationParameters.Add("lowerage", _min.ToString());
return new List<ModelClientValidationRule> { mcvrTwo };
}
}
public class MaximumAgeCheck : ValidationAttribute, IClientValidatable
{
private readonly int Max;
private readonly string _defaultErrorMessage = "";
public MaximumAgeCheck(int max, string defaultErrorMessage)
: base(defaultErrorMessage)
{
Max = max;
_defaultErrorMessage = defaultErrorMessage.Replace("{0}", Max.ToString());
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
DateTime dtV = (DateTime)value;
long lTicks = DateTime.Now.Ticks - dtV.Ticks;
DateTime dtAge = new DateTime(lTicks);
if (!(dtAge.Year >= Max && dtAge.Year <= 30))
{
return new ValidationResult(_defaultErrorMessage);
}
return ValidationResult.Success;
}
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,Max);
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
ModelClientValidationRule mcvrTwo = new ModelClientValidationRule();
mcvrTwo.ValidationType = "checkmaximumage";
mcvrTwo.ErrorMessage = _defaultErrorMessage;
mcvrTwo.ValidationParameters.Add("todaysdate", DateTime.Now.ToString("dd/MM/yyyy"));
mcvrTwo.ValidationParameters.Add("upperage", Max.ToString());
return new List<ModelClientValidationRule> { mcvrTwo };
}
}
The Jquery
(function ($) {
var mintodaysDateVal;
var maxtodaysDateVal;
var lowerageVal;
var upperageVal;
jQuery.validator.unobtrusive.adapters.add("checkminimumage", ['lowerage', 'todaysdate', 'upperage'], function (options) {
options.rules["checkminimumage"] = options.params;
mintodaysDateVal = options.params.todaysdate;
lowerageVal = options.params.lowerage;
options.messages["checkminimumage"] = options.message;
});
jQuery.validator.addMethod("checkminimumage", function (value, element, params) {
var currDate = mintodaysDateVal;
var sdoc = currDate.split('/');
var dobDate = value;
var sdob = dobDate.split('/');
//pass year,month,date in new Date object.
var vDOB = new Date(sdob[2], sdob[1] - 1, sdob[0]);
var vDOC = new Date(sdoc[2], sdoc[1] - 1, sdoc[0]);
//getAge user define function to calculate age.
var vYrs = getAge(vDOB, vDOC);
var result = false;
if (vYrs >= lowerageVal) { result = true; }
return result;
});
jQuery.validator.unobtrusive.adapters.add("checkmaximumage", ['lowerage', 'todaysdate', 'upperage'], function (options) {
options.rules["checkmaximumage"] = options.params;
maxtodaysDateVal = options.params.todaysdate;
upperageVal = options.params.upperage;
options.messages["checkmaximumage"] = options.message;
});
jQuery.validator.addMethod("checkmaximumage", function (value, element, params) {
var currDate = maxtodaysDateVal;
var sdoc = currDate.split('/');
var dobDate = value;
var sdob = dobDate.split('/');
var vDOB = new Date(sdob[2], sdob[1] - 1, sdob[0]);
var vDOC = new Date(sdoc[2], sdoc[1] - 1, sdoc[0]);
var vYrs = getAge(vDOB, vDOC);
var result = false;
if (vYrs <= upperageVal) { result = true; }
return result;
});
function getAge(oldDate, currDate) {
return currDate.getFullYear() - oldDate.getFullYear();
}
} (jQuery));
I hope this makes sense, I've read it over and its quite garbled... so i'll be happy to answer any comments.
Really useful code, but the ValidationResult IsValid method has some bugs. It doesn't handle future dates or blank dates. Plus it seems to have a hard coded limit to age 30 in - looks to be debug code? Anyway, I addressed those issues for my code and came up with the below:
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value == null)
{
return new ValidationResult(_defaultErrorMessage);
}
DateTime dtV = (DateTime)value;
long lTicks = DateTime.Now.Ticks - dtV.Ticks;
if (lTicks < 0)
{
return new ValidationResult(_defaultErrorMessage);
}
DateTime dtAge = new DateTime(lTicks);
if (!(dtAge.Year >= _min ))
{
return new ValidationResult(_defaultErrorMessage);
}
return ValidationResult.Success;
}
Take a look at the MVC Foolproof Validation library. You can find it in NuGet.
It has pretty much all the validation you need and is added via data annotations. It will intergrate nicely into the unobtrusive client side validation.
MVC3, Entity Framework 4.1 Code first.
Working with 2 tables
Model:
public class UniversityMaster
{
[Key]
public string UniversityId { get; set; }
public string UniversityName { get; set; }
}
public class ProgramMaster
{
[Key]
public string ProgramId { get; set; }
public string ProgramName { get; set; }
public string UniversityId { get; set; }
public virtual UniversityMaster University { get; set; } // navigation property
}
Dynamic expression for sorting (just to avoid a switch case statement):
public virtual IQueryable< ProgramMaster > GetQueryableSort(string sortField="", string sortDirection="")
{
IQueryable<ProgramMaster> query = _dbSet;
ParameterExpression pe = Expression.Parameter(typeof(ProgramMaster), string.Empty);
MemberExpression property = Expression.PropertyOrField(pe, sortField);
//get a exception here if the sort field is of navigation property (University.UniversityName)
LambdaExpression lambda = Expression.Lambda(property, pe);
if (sortDirection == "ASC")
orderbydir = "OrderBy";
else
orderbydir = "OrderByDescending";
MethodCallExpression call = Expression.Call(typeof(Queryable),
orderbydir, new Type[] { typeof(TEntity), property.Type }, query.Expression, Expression.Quote(lambda));
var returnquery = (IOrderedQueryable<ProgramMaster>)query.Provider.CreateQuery< ProgramMaster >(call);
return returnquery;
}
The page is displaying a grid with two columns Program Name and University Name using webgrid. The sorting work fine for Program Name column, however fails if sorted by University Name as this property is in UniversityMaster and the Expression.PropertyOrField searches this property in ProgramMaster. Here is the exception:
University.UniversityName' is not a member of type 'App.Core.Model.ProgramMaster
My question is how I make this work for navigation properties of my model class.
Hope I was able explain the scenario. Any help is appreciated.
Well that's because the MemberExpression is trying to call a member named Univerty.UniversityName on the parameter. What you want to do is call a member named Univerity on the parameter, then call UniversityName on that. Effectively, you need to iteratively resolve the property names.
public virtual IQueryable< ProgramMaster > GetQueryableSort(string sortField = "", string sortDirection = "")
{
IQueryable<ProgramMaster> query = _dbSet;
var propertyNames = sortField.Split(".");
ParameterExpression pe = Expression.Parameter(typeof(ProgramMaster), string.Empty);
Expression property = pe;
foreach(var prop in propertyName)
{
property = Expression.PropertyOrField(property, prop);
}
LambdaExpression lambda = Expression.Lambda(property, pe);
if (sortDirection == "ASC")
orderbydir = "OrderBy";
else
orderbydir = "OrderByDescending";
MethodCallExpression call = Expression.Call(
typeof(Queryable),
orderbydir,
new Type[] { typeof(TEntity), property.Type },
query.Expression,
Expression.Quote(lambda));
var returnquery = (IOrderedQueryable<ProgramMaster>)query.Provider.CreateQuery<ProgramMaster>(call);
return returnquery;
}
Microsoft has a DynamicQueryable class which can be used to dynamically construct certain portions of a LINQ query using strings. With this you can say myQuery.OrderBy("University.UniversityName") and it will handle building the expression. The same library also supports dynamic construction of SELECT and WHERE clauses.
You can find a copy of the source as part of the excellent EntityFramework.Extended package by Loresoft. Microsoft's file is at https://github.com/loresoft/EntityFramework.Extended/blob/master/Source/EntityFramework.Extended/Dynamic/DynamicQueryable.cs
I need some help with this one....
I have this simple model:
public class Candidat
{
public string LoginEmail { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "Prénom")]
public string FirstName { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "Nom")]
public string LastName { get; set; }
}
I also have a controller like this:
[Authorize]
public ActionResult Index(Candidat model)
{
if (model.LoginEmail == null)
{
model = null;
using (var db = new rhDB())
{
MembershipUser user = Membership.GetUser();
if (user != null)
{
model = (from m in db.Candidates where m.LoginEmail == user.Email select m).SingleOrDefault();
}
if (model == null)
{
model = new Candidat();
model.LoginEmail = user.Email;
model.Email = user.Email;
}
}
}
return View("MyProfileCandidate", model);
}
As you can see, I check if the user as an existing record in the database. If not, I create a new instance of the model and set some default values... Then, I pass it to an EditView.
The problem is that my view show with the error validation messages... For all required fields...
Of course, this is because those fields are empty and required... It seems like the view think I am posting back an invalid model... Is there a way to hide those validation message ?
Try clearing the model state if you intend to modify some of the values on your model in the POST action:
[Authorize]
public ActionResult Index(Candidat model)
{
if (model.LoginEmail == null)
{
model = null;
using (var db = new rhDB())
{
MembershipUser user = Membership.GetUser();
if (user != null)
{
ModelState.Clear();
model = (from m in db.Candidates where m.LoginEmail == user.Email select m).SingleOrDefault();
}
if (model == null)
{
ModelState.Clear();
model = new Candidat();
model.LoginEmail = user.Email;
model.Email = user.Email;
}
}
}
return View("MyProfileCandidate", model);
}
The reason for this is that HTML helpers will use model state values that were initially posted instead of those in the model. You could also clear individual fields in the model state: ModelState.Remove("FirstName");.
I had two fields some thing like phone number and mobile number. Some thing like..
[Required]
public string Phone { get; set; }
[Required]
public string Mobile{ get; set; }
But user can enter data in either one of it. One is mandatory. How to handle them i.e how to disable the required field validator for one field when user enter data in another field and viceversa. In which event i have to handle it in javascript and what are the scripts i need to add for this. Can anyone please help to find the solution...
One possibility is to write a custom validation attribute:
public class RequiredIfOtherFieldIsNullAttribute : ValidationAttribute, IClientValidatable
{
private readonly string _otherProperty;
public RequiredIfOtherFieldIsNullAttribute(string otherProperty)
{
_otherProperty = otherProperty;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var property = validationContext.ObjectType.GetProperty(_otherProperty);
if (property == null)
{
return new ValidationResult(string.Format(
CultureInfo.CurrentCulture,
"Unknown property {0}",
new[] { _otherProperty }
));
}
var otherPropertyValue = property.GetValue(validationContext.ObjectInstance, null);
if (otherPropertyValue == null || otherPropertyValue as string == string.Empty)
{
if (value == null || value as string == string.Empty)
{
return new ValidationResult(string.Format(
CultureInfo.CurrentCulture,
FormatErrorMessage(validationContext.DisplayName),
new[] { _otherProperty }
));
}
}
return null;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "requiredif",
};
rule.ValidationParameters.Add("other", _otherProperty);
yield return rule;
}
}
which you would apply to one of the properties of your view model:
public class MyViewModel
{
[RequiredIfOtherFieldIsNull("Mobile")]
public string Phone { get; set; }
public string Mobile { get; set; }
}
then you could have a controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel());
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
}
and finally a view in which you will register an adapter to wire the client side validation for this custom rule:
#model MyViewModel
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script type="text/javascript">
jQuery.validator.unobtrusive.adapters.add(
'requiredif', ['other'], function (options) {
var getModelPrefix = function (fieldName) {
return fieldName.substr(0, fieldName.lastIndexOf('.') + 1);
}
var appendModelPrefix = function (value, prefix) {
if (value.indexOf('*.') === 0) {
value = value.replace('*.', prefix);
}
return value;
}
var prefix = getModelPrefix(options.element.name),
other = options.params.other,
fullOtherName = appendModelPrefix(other, prefix),
element = $(options.form).find(':input[name="' + fullOtherName + '"]')[0];
options.rules['requiredif'] = element;
if (options.message) {
options.messages['requiredif'] = options.message;
}
}
);
jQuery.validator.addMethod('requiredif', function (value, element, params) {
var otherValue = $(params).val();
if (otherValue != null && otherValue != '') {
return true;
}
return value != null && value != '';
}, '');
</script>
#using (Html.BeginForm())
{
<div>
#Html.LabelFor(x => x.Phone)
#Html.EditorFor(x => x.Phone)
#Html.ValidationMessageFor(x => x.Phone)
</div>
<div>
#Html.LabelFor(x => x.Mobile)
#Html.EditorFor(x => x.Mobile)
#Html.ValidationMessageFor(x => x.Mobile)
</div>
<button type="submit">OK</button>
}
Pretty sick stuff for something so extremely easy as validation rule that we encounter in our everyday lives. I don't know what the designers of ASP.NET MVC have been thinking when they decided to pick a declarative approach for validation instead of imperative.
Anyway, that's why I use FluentValidation.NET instead of data annotations to perform validations on my models. Implementing such simple validation scenarios is implemented in a way that it should be - simple.
I know this question is not so hot, because it was asked relatively long time ago, nevertheless I'm going to share with a slightly different idea of solving such an issue. I decided to implement mechanism which provides conditional attributes to calculate validation results based on other properties values and relations between them, which are defined in logical expressions.
Your problem can be defined and automatically solved by the usage of following annotations:
[RequiredIf("Mobile == null",
ErrorMessage = "At least email or phone should be provided.")]
public string Phone{ get; set; }
[RequiredIf("Phone == null",
ErrorMessage = "At least email or phone should be provided.")]
public string Mobile { get; set; }
If you feel it would be useful for your purposes, more information about ExpressiveAnnotations library can be found here. Client side validation is also supported out of the box.
Since nobody else suggested it, I'm going to tell you a different way to do this that we use.
If you create a notmapped field of a custom data type (in my example, a pair of gps points), you can put the validator on that and you don't even need to use reflection to get all the values.
[NotMapped]
[DCGps]
public GPS EntryPoint
{
get
{
return new GPS(EntryPointLat, EntryPointLon);
}
}
and the class, a standard getter/setter
public class GPS
{
public decimal? lat { get; set; }
public decimal? lon { get; set; }
public GPS(decimal? lat, decimal? lon)
{
this.lat = lat;
this.lon = lon;
}
}
and now the validator:
public class DCGps : DCValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (!(value is GPS)) {
return new ValidationResult("DCGps: This annotation only works with fields with the data type GPS.");
}
//value stored in the field.
//these come through as zero or emptry string. Normalize to ""
string lonValue = ((GPS)value).lonstring == "0" ? "" : ((GPS)value).lonstring;
string latValue = ((GPS)value).latstring == "0" ? "" : ((GPS)value).latstring;
//place validation code here. You have access to both values.
//If you have a ton of values to validate, you can do them all at once this way.
}
}