C# 美国货币的客户端验证

C# 美国货币的客户端验证,c#,validation,asp.net-mvc-5,C#,Validation,Asp.net Mvc 5,我有一个ASP.NETMVC5Web应用程序,我需要接受用户输入的美元。一些有效的输入可能是: 100 $100.21 $ 1,234 $1,234.56 10,12 1o0.21 无效输入可能是: 100 $100.21 $ 1,234 $1,234.56 10,12 1o0.21 我的(简化)模型如下所示: public class Claim { [DisplayName("$ Amount)] [DataType(DataType.Currency)] [Requir

我有一个ASP.NETMVC5Web应用程序,我需要接受用户输入的美元。一些有效的输入可能是:

100
$100.21
$ 1,234
$1,234.56
10,12
1o0.21
无效输入可能是:

100
$100.21
$ 1,234
$1,234.56
10,12
1o0.21
我的(简化)模型如下所示:

public class Claim {
  [DisplayName("$ Amount)]
  [DataType(DataType.Currency)]
  [Required]
  [Range(0.0, 200000.0)]
  public decimal? DollarAmount { get; set; }
}
  @Html.LabelFor(model => model.DollarAmount, htmlAttributes: new { @class = "control-label col-md-3" })
  <div class="col-md-9">
    @Html.EditorFor(model => model.DollarAmount, new { htmlAttributes = new { @class = "form-control margin-bottom" } })
    @Html.ValidationMessageFor(model => model.DollarAmount, "", new { @class = "text-danger" })
  </div>
我的cshtml标记如下所示:

public class Claim {
  [DisplayName("$ Amount)]
  [DataType(DataType.Currency)]
  [Required]
  [Range(0.0, 200000.0)]
  public decimal? DollarAmount { get; set; }
}
  @Html.LabelFor(model => model.DollarAmount, htmlAttributes: new { @class = "control-label col-md-3" })
  <div class="col-md-9">
    @Html.EditorFor(model => model.DollarAmount, new { htmlAttributes = new { @class = "form-control margin-bottom" } })
    @Html.ValidationMessageFor(model => model.DollarAmount, "", new { @class = "text-danger" })
  </div>
@Html.LabelFor(model=>model.DollarAmount,htmlAttributes:new{@class=“control label col-md-3”})
@EditorFor(model=>model.DollarAmount,new{htmlAttributes=new{@class=“form control margin bottom”})
@Html.ValidationMessageFor(model=>model.DollarAmount,“,new{@class=“text danger”})
我使用这个建议构建了一个活页夹,可以将用户输入转换为十进制,但是客户端验证不允许用户输入美元符号或逗号。我需要做什么才能允许用户输入有效的货币值,但如果她输入了无效的值,我会警告她?我更喜欢在客户端进行尽可能多的验证

您可能想看看。帮助分配这种东西。至于你的问题,如果你想使用美元符号,你就不能将这个值作为十进制格式存储在数据库中,只能作为字符串

有几件事你可以做,使用bootstrap在你的文本框前面放置一个美元符号,使用
input group addon
。不确定它是否能正常工作,因为我看到您在文本框上设置了边距底部,告诉我您可能没有使用上面的引导表单标记

你可能想看看jQuery插件,它维护得很好,他们基本上“想到了我想要的一切”

// View

@Html.LabelFor(model => model.DollarAmount, htmlAttributes: new { @class = "control-label col-md-3" })
    <div class="col-md-9 input-group">
        <span class="input-group-addon">$</span>
        @Html.EditorFor(model => model.DollarAmount, new { htmlAttributes = new { @class = "form-control margin-bottom" } })
        @Html.ValidationMessageFor(model => model.DollarAmount, "", new { @class = "text-danger" })
    </div>


// Class

public class Claim {
  [DisplayName("$ Amount")]
  [DataType(DataType.Currency)]
   // {0:C} Will show as currency {0:N} to show Numbers
  [DisplayFormat(DataFormatString = "{0:C}", ApplyFormatInEditMode = true))] 
  [Required]
  [Range(0.0, 200000.0)]
  public decimal? DollarAmount { get; set; }
}
//查看
@LabelFor(model=>model.DollarAmount,htmlAttributes:new{@class=“controllabel col-md-3”})
$
@EditorFor(model=>model.DollarAmount,new{htmlAttributes=new{@class=“form control margin bottom”})
@Html.ValidationMessageFor(model=>model.DollarAmount,“,new{@class=“text danger”})
//阶级
公共类索赔{
[显示名称(“$Amount”)]
[数据类型(数据类型.货币)]
//{0:C}将显示为货币{0:N}以显示数字
[DisplayFormat(DataFormatString=“{0:C}”,ApplyFormatInEditMode=true))]
[必需]
[范围(0.0,200000.0)]
公共十进制?DollarAmount{get;set;}
}
另一个选项是使用javascript创建一个隐藏字段,该字段将从字符串复制到十进制,可以是您提交的字段,如下所示

// MODEL
public class Claim {
  [DisplayName("$ Amount")]
  [DataType(DataType.Currency)]
  [Required]
  [Range(0.0, 200000.0)]
  public decimal? DollarAmount { get; set; }
}


// View

@Html.HiddenFor(model => model.DollarAmount, new { @id = "DollarAmount" })

@Html.LabelFor(model => model.DollarAmount, htmlAttributes: new { @class = "control-label col-md-3" })
    <div class="col-md-9 input-group">
        <span class="input-group-addon">$</span>
        <input id="DollarSave" type="text" name="DollarSave" pattern="^\$?([0-9]{1,3},([0-9]{3},)*[0-9]{3}|[0-9]+)(.[0-9][0-9])?$" title="You must enter in proper currency">
        @Html.ValidationMessageFor(model => model.DollarAmount, "", new { @class = "text-danger" })
    </div>
<script type="text/javascript">
jQuery(document).ready(function($){
  $('#DollarSave').change(function(){ 
  var sourceField = $("#DollarSave").val(); //source field key
  $("#DollarAmount").val(sourceField); //destination field key
  $("#DollarAmount").change(); //destination field key
  });
});
</script>
//模型
公共类索赔{
[显示名称(“$Amount”)]
[数据类型(数据类型.货币)]
[必需]
[范围(0.0,200000.0)]
公共十进制?DollarAmount{get;set;}
}
//看法
@Html.HiddenFor(model=>model.DollarAmount,新的{@id=“DollarAmount”})
@LabelFor(model=>model.DollarAmount,htmlAttributes:new{@class=“controllabel col-md-3”})
$
@Html.ValidationMessageFor(model=>model.DollarAmount,“,new{@class=“text danger”})
jQuery(文档).ready(函数($){
$('#DollarSave').change(function(){
var sourceField=$(“#DollarSave”).val();//源字段键
$(“#DollarAmount”).val(源字段);//目标字段键
$(“#DollarAmount”).change();//目标字段键
});
});

Pool pro的回答对解决我的问题有很大帮助,但我无法让他的输入标记模式显示消息。它在JSIDdles中工作,但在我的Asp.Net视图模板中不起作用。因此,我用javascript进行了模式验证和消息更新。我还使用了不同的正则表达式。为了完整起见,我将我的解决方案发布在这里:

@Html.HiddenFor(model => model.DollarAmount, new { @id = "DollarAmount" })

@Html.LabelFor(model => model.DollarAmount, htmlAttributes: new { @class = "control-label col-md-3" })
<div class="col-md-9">
    <input id="DollarSave" type="text" name="DollarSave" class="form-control text-box single-line">
    <p id="BadDollarSave" class="text-danger"></p>
</div>

<script type="text/javascript">
jQuery(document).ready(function($){

    $('#DollarSave').on('blur', function () {
        validateDollarSave();
    });

    function validateMoney(inputId) { 
        var errorMsg = '';
        var currency = $('#DollarSave').val();
        var good = currency.match(/^(\$|\$ )?[0-9]{1,3}(?:(,[0-9]{3})*|([0-9]{3})*)(?:(\.|\.[0-9]{2}))?$/);
        if (!good) {
            errorMsg = "$ Amount must be US currency";
        } else {
            var num = currency.replace(/[, $]/g, "");
            $('#DollarAmount').val(num);
        }
        document.getElementById('BadDollarSave').innerHTML = errorMsg;
    };
});
</script>
@Html.HiddenFor(model=>model.DollarAmount,新的{@id=“DollarAmount”})
@LabelFor(model=>model.DollarAmount,htmlAttributes:new{@class=“controllabel col-md-3”})

jQuery(文档).ready(函数($){ $('DollarSave')。在('blur',函数(){ validateDollarSave(); }); 函数validateMoney(inputId){ var errorMsg=''; var currency=$('#DollarSave').val(); var good=currency.match(/^(\$\$)?[0-9]{1,3}(?:(,[0-9]{3})*.([0-9]{3})*)(?:(:(\.\.\.\.[0-9]{2}))?$/; 如果(!好){ errorMsg=“$Amount必须是美元”; }否则{ var num=货币。替换(/[,$]/g,”); $('DollarAmount').val(num); } document.getElementById('BadDollarSave')。innerHTML=errorMsg; }; });
您能否添加一个
[DisplayFormat]
?例如:
[DisplayFormat(DataFormatString=“{$#####、#####.#}”,ApplyFormatInEditMode=true)]
它似乎不起作用。当它显示声明时,在解析@Html.DisplayFor(modelItem=>item.DollarAmount)时抛出System.FormatException:“输入字符串的格式不正确”。我还尝试了[DisplayFormat(DataFormatString=“{0:C}”,ApplyFormatInEditMode=true)],它没有抛出,但也不允许我在输入字段中输入$。谢谢!虽然我无法让您的解决方案正常工作(该模式无法启动,可能是因为我使用的视图模板),但它为我指明了正确的方向,我使用了您的解决方案的一部分,我已经解决了问题!我会接受你的回答并在下面发布我的解决方案。很抱歉,在MVC 5中,将JS脚本放在一个文件中并在页面底部使用render script调用它更容易,否则它会在javascript之前调用脚本。实际上我是在这样做的。我展示它并不是为了让问题和答案简单。