سؤال

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?

هل كانت مفيدة؟

المحلول

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.");
    }
  }

نصائح أخرى

I found the simplest way:

@Html.ValidationMessageFor(model => model.IPv4NetworkMask, "You have entered incorrect IP")
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top