Format currency in asp-validation-for

Nishant Sharma 21 Reputation points
2022-03-13T23:28:14.253+00:00

How can I set the currency format for an asp-validation-for?

Model Book :

[DisplayFormat(DataFormatString = "{0:C}", ApplyFormatInEditMode = true)]
public double Price { get; set; }

View
<input asp-for="Book!.Price" class="form-control" />

How can i use <span asp-validation-for="Book.Price" class="text-danger"></span> since it does not handle format.

Developer technologies ASP.NET ASP.NET Core
{count} votes

Accepted answer
  1. Anonymous
    2022-03-15T08:06:35.497+00:00

    Hi @Nishant Sharma ,

    If you are using the asp-validation-for and it will use client validation jquery.validate js library to check the textbox value. It use the regex/^-?(?:\d+|\d{1,3}(?:[\s\.,]\d{3})+)(?:[\.,]\d+)?$/ to check the textbox. If you use DataFormatString to modify the format it will atuo add the $ at the input box which caused the validate failed.

    The recommended solution here is to place the currency indicator outside of the editable field (e.g. before or after).

    Like below examle:

    <div class="input-group mb-3">  
      <div class="input-group-prepend">  
        <span class="input-group-text">$</span>  
      </div>  
      <input type="text" class="form-control" asp-format="{0:#,###.00}"  aria-label="Amount (to the nearest dollar)" asp-for="Price">  
       
    </div>  
      
     <span asp-validation-for="Price" class="text-danger"  ></span>   
    

    Image:
    EgK58.png


1 additional answer

Sort by: Most helpful
  1. Nishant Sharma 21 Reputation points
    2022-03-15T14:07:10.533+00:00

    I was able to fix the formatting183295-4.png
    <div class="col-8">
    <div class="input-group">
    <div class="input-group-prepend">
    <span class="input-group-text">$</span>
    </div>
    <input asp-for="Book!.Price" asp-format="{0:#,###.00}" aria-label="Amount (to the nearest dollar)" class="form-control" />
    <span asp-validation-for="Book!.Price" class="text-danger"></span>
    </div>
    </div>

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.