Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data Annotation MVC 4 Digits

I'm trying to implement a field that accepts 4 digits or leave it as empty.

[RegularExpression(@"^(\d{4})$", ErrorMessage = "Enter a valid 4 digit Year")]
[Display(Name = "Year")]
public int Year { get; set; }

When entering more than 4 numbers the error message shows up. The problem is when I enter any value which is not a numbers or a mix of numbers and non-numbers the validation error message does not show up.

I have definitely missed something. Help me out here :)

like image 514
Warren Avatar asked Dec 15 '25 01:12

Warren


1 Answers

Warren,

Try to use nullable int, so it will allow co send data through if nothing is in model, See code below for implementation

public class TestModel
{
    [RegularExpression(@"^(\d{4})$", ErrorMessage = "Enter a valid 4 digit Year")]
    [Display(Name = "Year")]
    public int? Year { get; set; }
}

Updated: My view for this code where it works is as follows

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index</h2>

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>TestModel</legend>

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

        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

And my model with controller is:

 public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            var model = new TestModel();

            return View(model);
        }
}


    public class TestModel
    {
        [RegularExpression(@"^(\d{4})$", ErrorMessage = "Enter a valid 4 digit Year")]
        [Display(Name = "Year")]
        public int? Year { get; set; }
    }
like image 144
cpoDesign Avatar answered Dec 16 '25 18:12

cpoDesign



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!