Search code examples
c#validationasp.net-mvc-4unobtrusive-validation

How to validate string model property splitted in a few html text boxes?


I have a table in database which has 1 GUID column. It's mapped to entity as simple string property:

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

And I want the client to see this property as 4 textboxes? each of them contains a part of:

Code.Split(new[] {"-"}, StringSplitOptions.None)

I know how to validate this property by RegularExpressinAttribute if hole value will be displayed in 1 html textbox. But I want that it parsed on 4 parts before showing to user and combined together after user edit those textboxes. So can you, please, help me how to make validation on server and on client. Thank you!


Solution

  • You should create a view model for your view which has four seperate properties

    public class CreateCodeVm
    {
      [Required]
      public string CodePart1 { set;get;}
    
      [Required]
      public string CodePart2 { set;get;}
    
      [Required]
      public string CodePart3 { set;get;}
    
      [Required]
      public string CodePart4 { set;get;}
    }
    

    And you will use this view model to transfer data between your view and action methods. Once you read the value in your action method you can use it to save to your db where you might use the Entity class created by your ORM.

    When you have to show this to user, read the Guid and convert to a string then split.

    public ActionResult Edit(int id)
    {
      var vm = new CreateCodeVm();
      var guidVariable = GetGuidFromYourDataBaseSomeHave();
      var parts = guidVariable.ToString().Split('-');
      vm.CodePart1 = parts[0];
      vm.CodePart2 = parts[1];
      vm.CodePart3 = parts[2];
      vm.CodePart4 = parts[3];
    
      return View(vm);
    }
    

    and in your view

    @model CreateCodeVm
    @using(Html.BeginForm())
    {
      @Html.TextBoxFor(s=>s.CodePart1)
      @Html.ValidationMessageFor(s=>s.CodePart1)
    
      @Html.TextBoxFor(s=>s.CodePart2)
      @Html.ValidationMessageFor(s=>s.CodePart2)
    
       @Html.TextBoxFor(s=>s.CodePart3)
      @Html.ValidationMessageFor(s=>s.CodePart3)
    
      @Html.TextBoxFor(s=>s.CodePart4)
      @Html.ValidationMessageFor(s=>s.CodePart4)
      <input type="submit" />
    }
    

    And in your HttpPost action you can check for validation errors

    [HttpPost]
    public ActionResult Edit(CreateCodeVm model)
    {
      if(ModelState.IsValid)
      {
         //save and return(redirect result) something
      } 
      return View(model);
    }
    

    While this will address your issue of validating 4 separate strings, It might bring another issue. What if you 2 users enter the same value for all four parts ? You will generate the same Guid from that ? It might cause you problems if your db column is of type uniqueidentifier.