Search code examples
asp.net-mvc-3custom-validators

MVC3 C# custom validation message sending from server side


Good day. May be it is wrong way but it was the fastest way. So:

I have a model which store IP address (NetworkMask) as long (integer) (stored in mssql table) And then I need to implement entering and correcting IP address I added not mapped field (IPv4NetworkMask) into model:

    [NotMapped]
    public string IPv4NetworkMask{
        get{
            return ExtIP.LongToIPv4(NetworkMask);
        }
        set{
            NetworkMask=ExtIP.StringToIPv4(value);
        }
    }

and into view:

        <div class="editor-label">
            @Html.LabelFor(model => model.NetworkMask)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.IPv4NetworkMask)
            @Html.ValidationMessageFor(model => model.IPv4NetworkMask)
        </div>

Now everything works fine and when user entered incorrect network address I got an Exception inside StringToIPv4 and execution goes out of controller by

        if (!ModelState.IsValid)
            return View(NewModelObj);

But on client side I got message: "The value 'fdgdfgdf' is invalid." How can I change this message to something else?


Solution

  • If you want to do it on the business layer, you can use a custom validator.

    for example:

    public static ValidationResult ValidateIP(string inputIP)
    {
       bool isValid = false;
    
        try {
            ExtIP.StringToIPv4(inputIP);
            isValid = true;
        }
        catch {
        }
    
    
        if (isValid)
        {
          return ValidationResult.Success;
        }
        else
        {
          return new ValidationResult(
              "Ip is not in a correct format.");
        }
      }