1

I am having model as

public class GroupedIssueData
{

    [Range(0, double.MaxValue, ErrorMessage = "Please enter valid number")]
    public double IssueQty { get; set; }

    public double ReqQty { get; set; }

    public bool isSavings { get; set; }
}

This contains two properties as IssueQty and IsSaving, If the IsSaving is checked then IssueQty can be empty, If the IssueQty is not empty then IsSaving can be left blank. How can I validate this

My View is

<td>
    @Html.DisplayFor(m => m.MaterialData[i].ReqQty)
    @Html.HiddenFor(m => m.MaterialData[i].ReqQty)
</td>
<td>@Html.TextBoxFor(m => m.MaterialData[i].IssueQty, new { style = "width:70px" })@Html.ValidationMessageFor(m => m.MaterialData[i].IssueQty)</td>
<td class="text-center">@Html.CheckBoxFor(m => m.MaterialData[i].isSavings)</td>

And my Controller is

public async Task<ActionResult> GetWorkOrderMaterialDetails(IssueEntryModel m)
{
    if (!ModelState.IsValid)
    {
        // redirect
    }
    var model = new IssueEntryModel();
}

How can I redirect to the if the Model is not valid. Do I need to redirect to same controller. I want to retain the entered data.

My View is

Sandip Bantawa
  • 2,822
  • 4
  • 31
  • 47
Techonthenet
  • 157
  • 4
  • 12
  • Use a [foolproof](http://foolproof.codeplex.com/) `[RequiredIfTrue]` or similar validation attribute (or write your own) –  Mar 28 '16 at 02:41

3 Answers3

0

try this

`

 [Required]  
        [Range(18, 100, ErrorMessage = "Please enter an age between 18 and 50")]  
        public int Age { get; set; }  


    [Required]         
    [StringLength(10)]  
    public int Mobile { get; set; }            

    [Range(typeof(decimal), "0.00", "15000.00")]  
    public decimal Total { get; set; }  `

 if (ModelState.IsValid)  
        {  
            //
        }  
        return View(model);  

Validation to the Model

Custom Validation Data Annotation Attribute

Sanjay kumar
  • 1,653
  • 12
  • 18
0

You can make a custom validation e.g. RequiredIfOtherFieldIsNullAttribute like described here:

How to validate one field related to another's value in ASP .NET MVC 3

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;
}

}

And use it like that:

[RequiredIfOtherFieldIsNull("IsSavings")]
public double IssueQty { get; set; }
[RequiredIfOtherFieldIsNull("IssueQty")]
public bool IsSavings { get; set; }
Community
  • 1
  • 1
0

Use IValidatableObject

However your condition: If the IsSaving is checked then IssueQty can be empty, If the IssueQty is not empty then IsSaving can be left blank is bit confusing, but this might hint you anyways

public class GroupedIssueData : IValidatableObject
{
    [Range(0, double.MaxValue, ErrorMessage = "Please enter valid number")]
    public double IssueQty { get; set; }

    public double ReqQty { get; set; }

    public bool isSavings { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (!isSavings && IssueQty == 0)
        {
            yield return new ValidationResult("Error Message");
        }
    }
}

public async Task<ActionResult> GetWorkOrderMaterialDetails(IssueEntryModel m)
{
    if (!ModelState.IsValid)
    {
        return View(m);
        // redirect
    }

}
Sandip Bantawa
  • 2,822
  • 4
  • 31
  • 47
  • Thanks, How to redirect to show the validation results without loosing the data. Do I need to return via same controller or different controller? – Techonthenet Mar 26 '16 at 08:24