0

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?

2 Answers 2

1

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.");
    }
  }
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, I've just implement with custom attribute and data annotations. Some good code sample: asp.net/mvc/tutorials/older-versions/models-%28data%29/…
0

I found the simplest way:

@Html.ValidationMessageFor(model => model.IPv4NetworkMask, "You have entered incorrect IP")

Comments

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.