【发布时间】:2015-07-16 12:02:41
【问题描述】:
我的问题如下:
我有一个字段,您可以在其中插入一个正则表达式,我必须检查它是否是有效的正则表达式(有效:[0-9],无效:[)。在我的页面上,我还有一些其他字段具有验证规则,例如 [Required] 或 [StringLength],它们在客户端工作,但这个没有。
客户端验证javascript
function validateRegex() {
$.validator.addMethod("validateregex", function (value, element, params) {
var isValid = true;
if (value.length == 0) return true;
try {
var regex = new RegExp(value);
} catch (e) {
isValid = false;
}
console.log(isValid);
return isValid;
});
$.validator.unobtrusive.adapters.add("validateregex", [], function (options) {
options.rules["validateregex"] = true;
options.messages["validateregex"] = options.message;
});
}
在 ASP.NET MVC 属性中我有这个:
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata,
ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = "RegEx is not valid", // FormatErrorMessage(metadata.DisplayName),
ValidationType = "validateregex"
};
rule.ValidationParameters.Add("errormessage", rule.ErrorMessage);
yield return rule;
}
如果正则表达式正确/不正确,则返回 ValidationResult 的 IsValid 方法。
<script type="text/javascript" src="~/Scripts/regexvalidator.js"></script>
<script type="text/javascript">
$(document).ready(function () {
validateRegex();
//$("#saveSettings").on("click", function () {
// $("#optionForm").submit();
//});
});
</script>
在我的 .cshtml 中,在 $(document).ready 中,我调用了 validateRegex 函数。视野定义为:
<div class="form-group">
@Html.LabelFor(m => m.Regex, new { @class = "control-label" })
<div class="controls">
@Html.TextBoxFor(p => p.Regex, new { @class = "form-control", id = "regexField" })
@Html.ValidationMessageFor(p => p.Regex)
</div>
</div>
HTML 查看源代码:
<div class="controls">
<input type="text" value="" name="Regex" id="regexField" class="form-control">
<span data-valmsg-replace="true" data-valmsg-for="Regex" class="field-validation-valid"></span>
</div>
除此之外,所有其他验证规则都有效。
有人知道为什么吗?
【问题讨论】:
标签: javascript asp.net regex asp.net-mvc validation