在客户端验证的asp.net mvc5中,正则表达式不适用于名称

时间:2015-07-02 09:47:22

标签: c# regex asp.net-mvc-5 jquery-validate unobtrusive-validation

我有asp.net mvc5应用程序,我正在尝试验证我在c#模型类中定义的正则表达式。当用户填写表格时,我需要对单个输入字段进行客户端验证。我在在线网站上有测试表达并且它是正确的。无论我在现场说什么都没关系,它会变成红色并显示错误信息。

模型

[StringLength(50)]
[Required(ErrorMessage = "Required Title")]
[RegularExpression("(/^[a-z ,.'-]+$/i)", ErrorMessage = "Only Allowed Alphabet Character In Title"
[Display(Name = "Title")]
public string Title { get; set; }

html输出

<input class="form-control text-box single-line input-validation-error" data-val="true" data-val-length="The field Title must be a string with a maximum length of 50." data-val-length-max="50" data-val-regex="Only Allowed Alphabet Character In Title" data-val-regex-pattern="(/^[a-z ,.'-]+$/i)" data-val-required="Required Title" id="Title" name="Title" value="" type="text">

的JavaScript

 $(function () {

    jQuery.validator.unobtrusive.parse();

    jQuery.validator.unobtrusive.parse("#CreateStudentProfileForm");


});



$(document).ready(function () {

    $("#CreateStudentProfileForm").find("input,textarea,select").on('input', function () {

        var _currentElement = $(this).attr('id');

        var v = $("#CreateStudentProfileForm").validate().element("#" + _currentElement);

        alert("va   " + v);
    });

});

我在部分视图中的javaScript

1 个答案:

答案 0 :(得分:0)

我找到了以下的anaswer;

 [MaxLength(50)]
 [Required(ErrorMessage = "Required Title")]
 [RegularExpression("(^[a-z ,.'-]+$)", ErrorMessage = "Only Allowed Alphabet Character In Title")]
 [Display(Name = "Title")]
 public string Title { get; set; }

...

 $("#CreateStudentProfileForm").find("input,textarea,select").on('input', function () {

        var _currentElement = $(this).attr('id');

        var v = $("#CreateStudentProfileForm").validate().element("#" + _currentElement);
});