How do you validate only if there's input?
Using Asp.Net MVC3, I have many steps in a wizard where after every step I do a $.post to capture what was entered. The first two steps are simple and all fields are required no matter what.
The rest of the steps are not required. However, if step 3 has 10 input fields and entered values for 5 out of 10, then validations have to kick in (just for the 5 fields and display the errors for those 5 only). So in essense, things like [Required], [StringLength] and [RegEx] should kick in only if someone actually entered anything for those 5 fields. If nothing is entered, validations should be skipped.
I was thinking of naming or prefixing each step (div) with Required or Optional as
Hope there is an 开发者_StackOverflow社区answer.
If you divide each step on your wizard into a separate form, then validation can be performed when necessary on that step's form.
Please be aware that BY DEFAULT StringLength
and RegEx
attributes will only be validated when information is entered in that particular field. If the fields are blank, validation of those attributes will not occur.
As far as Required
attributes, I am unclear what you are asking. Are you saying that there are fields in a particular step which will be required based on a condition in another field? If so, then you must implement a conditionally required validator.
You can make your viewmodel implement IValidatableObject. The interface requires one function, IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
. MVC will validate the model first from any DataAnnotations, then on the Validate function on the model (so twice, which isn't always what you want).
For example,
public class Input : IValidatableObject
{
public string Name { get; set; }
// ... Other fields ...
public virtual IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
if (String.IsNullOrEmpty(Name))
{
// ... Validation rules ...
results.Add(new ValidationResult("Please enter a name.", new[] { "Name" }));
}
return results;
}
}
More information from Scott Guthrie's blog.
You could write custom a validation attribute and perform this validation logic in the IsValid
method where you have access to the value and could check whether the value is not null or empty and only then proceed with the default validation.
精彩评论