How to validate IP Address in MVC 3

I am trying to validate ip address using MVC 3. If user entered wrong ip address then page should show "wrong ip address message" to user. I searched a lot on internet but didnt get proper solution. Can you please help me... Thanks in advance.

Code For Model:

 [Display(Name = "EQ")]
    public string EQ { get; set; }

    [Display(Name = "EQD")]
    public string EQD { get; set; }

    [Display(Name = "BFX")]
    public string BFX { get; set; }

    [Display(Name = "SLB")]
    public string SLB { get; set; }

    [Display(Name = "Others")]
    public string Others { get; set; }

I want seperate 5 check boxes i.e. (EQ, EQD, BFX, SLB and Others).

Code of View:

<div class="editor-label" style="font-weight: bold">
        @Html.LabelFor(model => model.EQ)
    </div>
    <div class="editor-field">
        @Html.CheckBoxFor(Model => Model.EQ)
        @Html.ValidationMessageFor(model => model.EQ)
    </div>
    <div class="editor-label" style="font-weight: bold">
        @Html.LabelFor(model => model.EQD)
    </div>
    <div class="editor-field">
        @Html.CheckBoxFor(Model => Model.EQD)
        @Html.ValidationMessageFor(model => model.EQD)
    </div>
    <div class="editor-label" style="font-weight: bold">
        @Html.LabelFor(model => model.BFX)
    </div>
    <div class="editor-field">
        @Html.CheckBoxFor(Model => Model.BFX)
        @Html.ValidationMessageFor(model => model.BFX)
    </div>
    <div class="editor-label" style="font-weight: bold">
        @Html.LabelFor(model => model.SLB)
    </div>
    <div class="editor-field">
        @Html.CheckBoxFor(Model => Model.SLB)
        @Html.ValidationMessageFor(model => model.SLB)
    </div>
    <div class="editor-label" style="font-weight: bold">
        @Html.LabelFor(model => model.Others)
    </div>
    <div class="editor-field">
        @*@Html.EditorFor(model => model.Others)*@
        @Html.CheckBoxFor(Model => Model.Others)
        @Html.ValidationMessageFor(model => model.Others)
    </div>

Upvotes: 0

Views: 2487

Answers (3)

Brett Maiwald
Brett Maiwald

Reputation: 41

This guy has a great method for MVC https://codingjourneyman.com/2015/01/08/model-validation-in-asp-net-mvc/

public class IPAddressModel
{
    [Required]
    [Display(Name = "Your name")]
    public string Name { get; set; }

    [IpAddress]
    [Required]
    [Display(Name = "Your IP address")]
    public string IPAddress { get; set; }
}

Upvotes: 1

Julien Canuel
Julien Canuel

Reputation: 13

In your model

[RegularExpression(@"^(?:[0-9]{1,3}.){3}[0-9]{1,3}$")]

public string AssignedIP { get; set; }

Upvotes: 1

Jakub Holovsky
Jakub Holovsky

Reputation: 6772

I recommend using IPAddress.TryParse()

Determines whether a string is a valid IP address.

http://msdn.microsoft.com/en-us/library/system.net.ipaddress.tryparse(v=vs.110).aspx

Upvotes: 1

Related Questions