Handling placeholders using unobtrusive validation

折月煮酒 提交于 2019-12-10 23:17:35

问题


I have a form that has placeholders for input fields. It uses html5 placeholder attribute and javascript placeholder fallback. I use unobtrusive validation like so:

    [DisplayName("")]
    [Required(ErrorMessage = "Please enter a name")]
    [StringLength(maximumLength: 20, MinimumLength = 1, ErrorMessage = "max length is 20 chars.")]
    public string UserName { get; set; }

    [DisplayName("")]
    [Required(ErrorMessage = "Please enter a comment.")]
    [StringLength(maximumLength: 350, MinimumLength = 1, ErrorMessage = "max length is 350 chars.")]
    public string CommentText { get; set; }

The problem is that when using IE the placeholders are counted as characters in the input fields so there is no validation and the form can be submitted when nothing is entered.

Is there some way I can add a condition to the UserName annotations that restricts a specified string. For example "Enter username here.."

I would like to avoid writing a custom property validator if this is possible.

Thanks in advance.

EDIT. Solved using regular expressions:

[RegularExpression("^((?!My_Placeholder_Text).|\n)*$", ErrorMessage = "Please enter text")]

回答1:


How about using a regex attribute to make sure the string you are looking for is not in the submitted string? The following question has examples of expressions that accomplish that: RegEx to exclude a specific string constant



来源:https://stackoverflow.com/questions/11882475/handling-placeholders-using-unobtrusive-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!