2

I am trying to figure out the proper way to model and validate a form with multiple form tags and multiple submit buttons using ASP.Net Core 2. What I have is a form where a user can either enter their username and password and sign in OR enter their first name, last name and cell number and sign up. Here is my model:

public class Landing
{
    [Required]
    public string Username { get; set; }
    [Required]
    public string Password { get; set; }
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
    [Required]
    public string CellNumber { get; set; }
}

Here is my relevant razor view code:

@model MyApp.ViewModels.Landing

<form method="post">
    <div>
        <input asp-for="Username" type="text" />
    </div>
    <div>
        <input asp-for="Password" type="password" />
    </div>
    <div>
        <input type="submit" value="Sign In" />
    </div>
</form>

<form method="post">
    <div>
        <input asp-for="FirstName" type="text" />
    </div>
    <div>
        <input asp-for="LastName" type="text" />
    </div>
    <div>
        <input asp-for="CellNumber" type="text" />
    </div>
    <div>
        <input type="submit" value="Sign Up" />
    </div>
</form>

Now the problem I run into is with my validation. Because all my fields are marked with the [Required] attribute, when I submit the form using either submit button, it's validating all 5 fields. What I want to do is validate UserName and Password only, IF the first submit button is pushed OR validate FirstName, LastName and CellNumber only, IF the second submit button is pushed. How can I achieve this?

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
Icemanind
  • 47,519
  • 50
  • 171
  • 296

1 Answers1

4

I would break my models into two class and then use a ViewModel instead:

public class SignIn
{
    [Required]
    public string Username { get; set; }
    [Required]
    public string Password { get; set; }
}

public class SignUp
{
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
    [Required]
    public string CellNumber { get; set; }
}

public class LandingViewModel
{
    public SignIn SignIn { get; set; }
    public SignUp SignUp { get; set; }
}

Then:

@model MyApp.ViewModels.LandingViewModel
SignIn.Username, SignIn.Password, SignUp.FirstName,...
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
  • Just so you know, the modelbinder will only new up classes if there's at least one property value posted. In other words, if you submit none of the properties for `SignUp`, then that will be null. If you design your form properly, this can be used to determine which form the user submitted without separate buttons. – Chris Pratt May 24 '18 at 13:40