MVC 3 jQuery 유효성 검사 / 숫자 / 십진수 필드의 전역 화
Web.config 파일에서 세계화 culture = "da-DK"를 사용하는 경우 jQuery 유효성 검사가 작동하지 않습니다.
덴마크에서는 제품 가격을 쓸 때 US 방식 19.95 대신 19,95 표기법을 사용하는데, 이로 인해 해결할 수없는 문제가 생겼습니다.
VS2010, 새로운 MVC 3 프로젝트를 시작하고 homeController, Product 클래스 및 간단한 표준 편집보기를 추가했으며 오류가 이미 있습니다.
제품 등급 :
public class Product
{
public string name { get; set; }
public string itemNo { get; set; }
public decimal price { get; set; }
}
HomeController :
public class homeController : Controller
{
public ActionResult Index()
{
var product1 = new Product { name = "Testproduct", itemNo = "PRD-151541", price = 19 };
return View(product1);
}
}
인덱스보기 :
@model WebUI.DomainModel.Product
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Product</legend>
<div class="editor-label">
@Html.LabelFor(model => model.name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.name)
@Html.ValidationMessageFor(model => model.name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.itemNo)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.itemNo)
@Html.ValidationMessageFor(model => model.itemNo)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.price)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.price)
@Html.ValidationMessageFor(model => model.price)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
결과:
안타깝게도 여기에 이미지를 제출할 수 없습니다. 결과를 보려면 다음 링크를 따르십시오. http://www.designvision.dk/temp/mvc3_razor_validation_error.gif
따라서 웹 사이트를 실행할 때 필드는 올바른 문화 정의 인 19,00으로 설정되지만 저장하려고하면 유효성 검사가 실패합니다.
도와주세요...
Microsoft 의 jQuery Globalization 플러그인 을 사용해 볼 수 있습니다 .
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.glob.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/globinfo/jquery.glob.da-dk.js")" type="text/javascript"></script>
<script type="text/javascript">
$.validator.methods.number = function (value, element) {
return !isNaN($.parseFloat(value));
}
$(function () {
$.preferCulture('da-DK');
});
</script>
플러그인 이름이 변경되고 이동 되었으므로 Globalize 를 사용해야합니다 (2012 년 3 월).
<script src="@Url.Content("~/Scripts/jquery.globalize/globalize.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.globalize/cultures/globalize.culture.da-DK.js")" type="text/javascript"></script>
<script type="text/javascript">
$.validator.methods.number = function (value, element) {
return !isNaN(Globalize.parseFloat(value));
}
$(document).ready(function () {
Globalize.culture('da-DK');
});
</script>
Scott Hanselman 블로그 게시물 에 대한 자세한 내용
선택적 요소 지원 으로 https://github.com/jquery/globalize의 현재 버전에 대한 업데이트 된 스크립트
$.validator.methods.number = function (value, element) {
return this.optional(element) || !isNaN(Globalize.parseFloat(value));
}
$(function () {
Globalize.culture('%%culture%%');
});
@shatl은 오늘 현재 정답을 가지고 있습니다. 범위 속성에 대한 참고 사항은 아래에 표시된 해킹이 필요합니다. 추가 할 전체 코드는 다음과 같습니다.
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript" src="~/Scripts/globalize.js"></script>
<script type="text/javascript" src="~/Scripts/globalize.culture.fr-FR.js"></script>
<script type="text/javascript">
$.validator.methods.number = function (value, element) {
return this.optional(element) ||
!isNaN(Globalize.parseFloat(value));
}
$(document).ready(function () {
Globalize.culture('fr-FR');
});
jQuery.extend(jQuery.validator.methods, {
range: function (value, element, param) {
//Use the Globalization plugin to parse the value
var val = $.global.parseFloat(value);
return this.optional(element) || (
val >= param[0] && val <= param[1]);
}
});
</script>
}
이 주제에 대한 Scott Hanselman의 블로그에있는 조언을 따랐습니다. 여기에서 이에 대해 읽을 수 있습니다.
나는 jQuery Global 대신 Globalize를 사용하기 위해 약간의 변경을해야했다 (이제 jQuery Global은 죽었다). 도움이되는 경우를 대비하여 다음 블로그 게시물에 작성했습니다.
http://icanmakethiswork.blogspot.co.uk/2012/09/globalize-and-jquery-validate.html
나중에 참조하기 위해 저에게 효과가 있었던 것은 다음과 같습니다.
올바른 jQuery 버전과 올바른 문화를 설정해야합니다.이 예에서는 덴마크어입니다.
값에 마침표가 없을 수 있으면 주석의 주석 처리를 제거하십시오.
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.globalize/globalize.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.globalize/cultures/globalize.culture.da-DK.js")"
type="text/javascript"></script>
<script type="text/javascript">
$.validator.methods.number = function (value, element) {
// if (value.indexOf(".") >= 0) {
// return false;
// }
return (Globalize.parseFloat(value));
}
$(document).ready(function () {
Globalize.culture('da-DK');
});
jQuery.extend(jQuery.validator.methods, {
range: function (value, element, param) {
//Use the Globalization plugin to parse the value
var val = Globalize.parseFloat(value);
return this.optional(element) || (val >= param[0] && val <= param[1]);
}
});
</script>
이 페이지에 감사드립니다. 많은 문제를 해결해주었습니다. 글로벌화 코드를 수정해야했습니다. 스웨덴 문화는 점을 구분자로 받아들이지 않지만 parseFloat가 기본 javasacript 구문 분석 점을 사용하기 때문에 십진수 구분자로 인식되지만 서버 측에서는 거부됩니다. 이 문제를 해결하려면 다음과 같이 parseFloat를 재정의합니다.
Globalize.orgParaseFloat = Globalize.parseFloat;
Globalize.parseFloat = function(value) {
var culture = this.findClosestCulture();
var seperatorFound = false;
for (var i in culture.numberFormat) {
if (culture.numberFormat[i] == ".") {
seperatorFound = true;
}
}
if (!seperatorFound) {
value = value.replace(".", "NaN");
}
return this.orgParaseFloat(value);
};
I've open a ticket at their Github so maybe this will be fixed
after some research... I found a solution.
Web.config in <system.web>
add
<globalization culture="auto" uiCulture="auto" enableClientBasedCulture="true"/>
Extend HtmlHelper class
namespace System.Web.Mvc
{
public static class LocalizationHelper
{
public static IHtmlString MetaAcceptLanguage(this HtmlHelper html)
{
var acceptLang = HttpUtility.HtmlAttributeEncode(Thread.CurrentThread.CurrentUICulture.ToString());
return new HtmlString(string.Format("<meta name=\"accept-language\" content=\"{0}\"/>", acceptLang));
}
}
}
_Layout.cshtml at the end of <head>
add
@Html.MetaAcceptLanguage();
<script type="text/javascript">
$(document).ready(function () {
var data = $("meta[name='accept-language']").attr("content");
$.global.preferCulture(data);
});
</script>
After these changes I'm able to manipulate decimal numbers with my web gui.
Regards, Giacomo
i'm from argentina, and i'm fighting with this problem a long time ago, we use "," as decimal separator, if you write "comma" javascript validation fails, but if you put ".", model will receibe a number translated to integer (55.60 will be 5560)
I solved out this problem with this simply solution:
1st- I upgraded jquery validation librarys, using new cdn addresses from: http://jqueryvalidation.org/
the links that I included on my javascript are this:
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/additional-methods.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/additional-methods.min.js"></script>
and if you want it in a specific language (in my case Spanish) add this line too:
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/localization/messages_es.js"></script>
Replace ES with the language you want.
2nd- If you want to allow numeric keypad decimal, you must replace "." with "," to work properly, add this code to your page to do that automatically:
$('#txtCurrency').keyup(function () {
$('#txtCurrency').val($('#txtCurrency').val().replace(/\./g, ','));
});
Presto, problem solved.
Bye.
No plugins
I think the easiest way to workaround this without any plugin is by just overriding the default validation, like this:
<script type="text/javascript">
$.validator.methods.number = function (value, element) {
var regex = /^(\d*)(\,\d{1,2})?$/; //99999,99
return regex.test(value);
}
</script>
If you look at the source code of jquery.validate.js
you will see that it just tests a regex like the code above, plus it validates if the element is optional:
'developer tip' 카테고리의 다른 글
Form의 Closing 이벤트에서 BackgroundWorker를 중지하는 방법은 무엇입니까? (0) | 2020.11.15 |
---|---|
행이없는 경우에만 삽입 (0) | 2020.11.15 |
배열의`length` 속성을 읽는 것이 자바 스크립트에서 그렇게 비싼 작업입니까? (0) | 2020.11.15 |
Zookeeper 3.4.6과 함께 Kafka 0.8.1을 사용할 때 LeaderNotAvailableException으로 실행 (0) | 2020.11.15 |
"삭제 표시"항목은 언제 / 어떻게 최종적으로 제거됩니까? (0) | 2020.11.15 |