Prevent ModelState.IsValid from validating attached entities?

1.5k views Asked by At

Is there a way to override ModelState.IsValid?

Some of the entities to be validated are just attached entities, so all the fields except the ID are not to be validate as the entity is in state Unchanged.

Is there a way to do this?
Has anyone faced this issue before?

Update

Say I have the following action:

[HttpPost]
public ActionResult SaveEntity(MyEntity entity)
{
    var isValid = ModelState.IsValid; //false
}

Since the model validates all properties and all descendant properties of entity, there has to be a way to check on each entity of those descendants, whether it's attached to the context, and if it is, remove error from ModelState, something like the following:

public ActionResult TryValidateDetachedModel(MyEntity entity, DbContext context)
{
    foreach (var ms in ModelState.Where(ms => ms.Value.Errors.Any()).ToArray())            
    // should iterate over something like GetAllEntityTypesMetadata()
    {
        var entity = GetEntityFromMetadata(ms);
        if (context.Entry(entity).State == EntityState.Unchanged)
        {
             ms.Value.Errors.Clear();                
        }
    }
}

What I'm trying to do in the above pseudo code is to check the entities in the validation chain, and if one of them is attached as Unchanged, skip validation / remove its errors.

Right now I have to do it hard-coded manually by checking ModelState.Key, I'm looking for a more generic and efficient way.

2

There are 2 answers

0
tratatun On BEST ANSWER

To clear all errors use next

ModelState.Clear();

regards

0
Sean On

Here's what I do to ensure the validation only applies to the current entity:

        foreach (var key in ModelState.Keys)
            if (key.Split('.').Length > 2)
                ModelState[key].Errors.Clear();

        if (!ModelState.IsValid)
            return BadRequest(ModelState);

The check for the occurrences of . means: if the modelstate key is something like currentDTO.relatedDTO.field then that validation error is ignored (cleared). If it's just id or currentDTO.validateThisField, then it doesn't get cleared.