Tuesday 31 October 2017

Decimal TextBox (Decimal number with two places) Validation using Data Annotations in ASP.Net MVC

Decimal TextBox (Decimal number with two places) Validation

Description:

In this example we explain that how to validate Decimal number with two places using Data Annotation in Asp.Net MVC.or how to validate TextBox with allow only Decimal number in MVC razor using Data Annotation. Or Regular Expression for the Decimal number with two places validation in MVC using Data Annotation. Here we demonstrate that how to perform Decimal TextBox validation with maximum up to two decimal places validation in MVC.

Model:
public class EmployeeModel
    {
        [Display(Name = "Expenses:")]
        [Required(ErrorMessage = "Expenses is required.")]
        [RegularExpression(@"^[0-9]+(\.[0-9]{1,2})$", ErrorMessage = "Valid Decimal number with maximum 2 decimal places.")]
        public string Expenses { get; set; }
    }

Controller: 

public class EmployeeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(EmployeeModel employee)
        {
            return View();
        }
    }

View:

@model Decimal_Validation_MVC.Models.PersonModel

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title>Decimal TextBox (Decimal number with two places) Validation using Data Annotations in ASP.Net MVC</title>
    <style type="text/css">
        body {
            font-family: Arial;
            font-size: 10pt;
        }
        .error {
            color: red;
        }
    </style>
</head>
<body>
    @using (Html.BeginForm("Index", "Employee", FormMethod.Post))
    {
        <table>
            <tr>
                <td>@Html.LabelFor(m => m.Expenses)</td>
                <td>@Html.TextBoxFor(m => m.Expenses)</td>
                <td>@Html.ValidationMessageFor(m => m.Expenses, "", new { @class = "error" })</td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" value="Submit"/></td>
                <td></td>
            </tr>
        </table>
    }
</body>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
</html>


This entry was posted in :

0 comments:

Post a Comment