Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

decimal data entery in ASP MVC

public Decimal SalePrice { get; set; }

and

<%= Html.TextBoxFor(Model => Model.SalePrice) %>

What is a good way to ensure validation or proper input entry from the user? Things like only allow numeric enteries and upto two decimal points?

like image 770
VoodooChild Avatar asked Feb 25 '23 16:02

VoodooChild


1 Answers

A regular expression like the following should work:

\A\d+(\.\d{1,2})?\Z

This matches input like:

2.00
25.70
04.15
2.50
525.43
423.3
52

And, as Mike suggested, you could use this in a data validation attribute:

[RegularExpression(@"\A\d+(\.\d{1,2})?\Z", ErrorMessage="Please enter a numeric value with up to two decimal places.")]
public Decimal SalePrice { get; set; }

Edit: In response to your two questions:

1) This validates on submit right and not when we lose focus of that field?

Assuming all you've added is the attribute, then yes validation occurs on submit. Technically, validation occurs once the form parameters are bound to the model. However, to actually make use of this, you need to check the validation parameter in your controller:

public ActionResult MyController(MyModel model)
{
    if (ModelState.IsValid)
    {
        // do stuff
    }
    else
    {
        // Return view with the now-invalid model
        // if you've placed error messages on the view, they will be displayed
        return View(model);
    }
}

To have the validation occur client-side in addition to server-side, you'd need to use javascript. A basic example of this using Microsoft AJAX validation is at Scott Gu's blog.

2) Can you show me the regex where the max entry cannot exceed 100.00 and min entry cannot be below 1.00

You could probably do this in regex somehow, but regex isn't really designed for anything more than pattern matching. A better way to do this would be to add a range validation attribute, in addition to your regex attribute. So now your property would look like:

[RegularExpression(@"\A\d+(\.\d{1,2})?\Z", ErrorMessage="Please enter a numeric value with up to two decimal places.")]
[Range(1.00m, 100.00m)]
public Decimal SalePrice { get; set; }

The above code is untested but the general approach should work.

like image 68
Pandincus Avatar answered Mar 08 '23 10:03

Pandincus