1

I am facing an issue when validating a form on ASP.

I have 2 models Person and Address. Each of them have their specific forms to add entries using EF Core.

In Person form I need hidden inputs to keep track of potential Address related data (It is perfectly fine there is no Address). To that matter I use hidden input fields but because the Address model have validation annotations, the generated markup reflects it which puts ModelState.IsValid to false upon validation unless, of course, I am editing a person with valid Address data.

I also tried to set Person.Address to null in the specific situation where it should be just before actually checking its value and it does not work. Probably it is already too late for ModelState to update by then.

if (Person.Address is not null && Person.Address.Id == 0)
    Person.Address = null;

if (ModelState.IsValid)
    // Further code to save data in DB
else
    // Code to redisplay the page

I would like to know if there is a way to tell ASP not to validate/ignore specific input fields but still allow me to keep a piece of data?

Thank you very much.

Edit: As per demand in the comments I add the classes with annotation

The Person

public class Person
{
  [Key]
  public int Id { get; set; }

  [Required]
  public string FirstName { get; set; }

  [Required]
  public string LastName { get; set; }

  [Range(0, 150)]
  public int Age { get; set; }

  public Address Address { get; set; }
}

The address class

public class Address
{
  [Key]
  public int Id { get; set; }

  [Required, MaxLength(50)]
  public string Street { get; set; }

  [Required, MaxLength(50)]
  public string City { get; set; }

  [Required, MaxLength(50)]
  public string Country { get; set; }
}
1
  • Can you show the classes pls with anotations? Commented Jun 20, 2021 at 12:29

3 Answers 3

4

OK Problem solved. I found some interesting doc.

Thanks for the propositions.

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

3

Also you can use this attribute as a prop header [ValidateNever]

If you're using FluentValidator etc When() is another thing

Doc : ValidateNever on .net core

Comments

0

You can skip data annotations on those fields which you don't want to validate.

2 Comments

thanks for the proposition. That said, iy is not a valid solution because I want them in the Address specific form.
You can apply dynamic model state errors then in address form using ModelState.AddModelError

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.