Disable Required validation attribute under certain circumstances
This problem can be easily solved by using view models. View models are classes that are specifically tailored to the needs of a given view. So for example in your case you could have the following view models:
public UpdateViewView
{
[Required]
public string Id { get; set; }
... some other properties
}
public class InsertViewModel
{
public string Id { get; set; }
... some other properties
}
which will be used in their corresponding controller actions:
[HttpPost]
public ActionResult Update(UpdateViewView model)
{
...
}
[HttpPost]
public ActionResult Insert(InsertViewModel model)
{
...
}
ASP.NET MVC. How disable required validation based on a parameter?
You can either create your own custom validation attribute or use MVC Foolproof Validation and then do:
class MyClass
{
public int Selector {get;set;} // 1 or 2
[RequiredIf("Selector == 1", ErrorMessage = "Your Error Message")]
public string A_required_for_1 {get;set;}
[RequiredIf("Selector == 1", ErrorMessage = "Your Error Message")]
public string B_required_for_1 {get;set;}
[RequiredIf("Selector == 2", ErrorMessage = "Your Error Message")]
public string C_required_for_2 {get;set;}
[RequiredIf("Selector == 2", ErrorMessage = "Your Error Message")]
public string D_required_for_2 {get;set;}
[Required("Your Error Message")]
public string E_Required_for_both_selectors {get;set;}
}
As mentioned by Win it does not seem to have been in active development for a while so you may want to go down the route of creating your own custom validation attribute, which does require more work but you can have a finer control over the validation itself. Choose depending on your needs.
For a custom validation attribute you could do something like this:
public class RequiredIfOtherProperty : ValidationAttribute
{
private readonly string _otherPropertyName;
private readonly string _compareValue;
public RequiredIfOtherProperty(string otherPropertyName, string compareValue)
{
_otherPropertyName = otherPropertyName;
_compareValue = compareValue;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var otherProperty = validationContext.ObjectType.GetProperty(_otherPropertyName);
if (otherProperty == null)
{
return new ValidationResult($"Property '{_otherPropertyName}' does not exist");
);
var otherPropertyValue = otherProperty.GetValue(validationContext.ObjectInstance, null);
if (!_compareValue.Equals(otherPropertyValue))
{
return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
}
return null;
}
}
It should give you a rough idea on what you can do and you can change the actual validation to however you like. You can then use it like a normal attribute e.g.
[RequiredIfOtherProperty("SomeProperty", "ValueToCompareWith")]
Ignore Required attribute when saving on edit page
I ended up doing this in my action method:
ModelState.Remove("User.Password");
Now my code runs fine, only raising validation errors on the "Name" field, which is what I wanted..
Disable required attribute
You can move the common properties to an interface and make each one decide if it's required or not.
public interface IParent
{
string Firstname { get; set; }
string Lastname { get; set; }
string Address { get; set; }
string Town { get; set; }
string Password { get; set; }
}
public class ShoppingParent : IParent
{
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Address { get; set; }
public string Town { get; set; }
public string Password { get; set; }
}
public class PasswordRequiredParent : IParent
{
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Address { get; set; }
public string Town { get; set; }
[Required]
public string Password { get; set; }
}
Disable Client Side Validation EditorFor
You have the Attribute [Required]
on the Model. One approach would be to create a separate model for each instance where you want it to be validated or not. See: https://stackoverflow.com/a/5367788/4501281
Disable validation on certain fields
I like to break it down and make a base model with all the common data and inhierit for each view:
class UserBaseModel
{
int ID { get; set; }
[Required]
string Name { get; set; }
[Required]
string Email { get; set; }
// etc...
}
class UserNewModel : UserBaseModel
{
[Required]
string Password { get; set; }
[Required]
string ConfirmPassword { get; set; }
}
class UserEditModel : UserBaseModel
{
string Password { get; set; }
string ConfirmPassword { get; set; }
}
Interested to know if there is a better way as well although this way seems very clean an flexible.
Related Topics
Automatic Enhancement of Scanned Images
Remove Surrounding Whitespace from an Image
How to Return a File (Filecontentresult) in ASP.NET Webapi
Merge Multiple Lists into One List With Linq
How Does Httpcontext.Current.User.Identity.Name Know Which Usernames Exist
How to Get Number of Rows Using Sqldatareader in C#
Sending Array of Bytes from Client to Server
How to Upload File to Server With Http Post Multipart/Form-Data
Asp.Net Core Identity Successful Login Redirecting Back to Login Page
System.Collections.Generic.List Does Not Contain a Definition for 'Select'
C# How to Check If a Url Exists/Is Valid
How to Store List of Data from Database to Arraylist or List in C#
How to Get the Specific Column in Excel Worksheet Using Documentformat.Openxml C#
How to Upload a Excel File to SQL Database Table Using C# Windows Form Application
Calling a Function from Another Class in C#/.Net MVC App
Browser Back Button Navigates to Login Page When User Is Still Logged In