Revious
Revious

Reputation: 8146

MVC and HTML5 Validation: conflict with the decimal format

I've got an input element:

View

<input 
type="number" 
min="0" 
max="100" 
step="1" 
value="@Model.Percentage" 
name="Percentage" />

Model

[Required][Range(0.2,10000)][DisplayFormat(DataFormatString = "{0:n2}", ApplyFormatInEditMode = true)]
public decimal? Percentage { get; set; }

In this way the input type stays empty in the browser.

I can force it by replacing the comma with a dot in the percentage ToString.

But then the DataAnnotations don't work any more.

Also have a look to HTML5 rendered input and the default MVC rendered input:

<input 
class="text-box single-line 
input-validation-error" 
data-val="true" 
data-val-number="The field Percentage must be a number." 
data-val-range="The field Percentage must be between 0 and 100." 
data-val-range-max="100" data-val-range-min="0" 
data-val-required="The field Percentage is mandatory" 
id="Percentage" name="Percentage" type="text" value="0,0" 
aria-required="true" 
aria-invalid="true" 
aria-describedby="Percentage-error Percentage-error Percentage-error Percentage-error">

<input type="number" 
min="0" 
max="100" 
step="1" 
value="1" 
name="Percentage" 
aria-invalid="false" 
aria-describedby="Percentage-error Percentage-error" 
class="valid">

Upvotes: 1

Views: 1708

Answers (1)

severin
severin

Reputation: 5493

Use MVC html helpers instead:

@Html.TextBoxFor(m => m.Percentage)

You can add attributes to the MVC-generated markup like this:

@Html.TextBoxFor(m => m.Percentage, new { @type = "number", @step="1", @min = "0", @max = "100" })

Upvotes: 1

Related Questions