URLとして使えない文字が含まれているのを検出する
執筆日時:
[Url]という属性を作成。 \"'|*`^><)(}{][#%;/?:@&=+$,. が含まれていたら IsValid() => false を返す。
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public sealed class UrlAttribute
: ValidationAttribute, IClientValidatable
{
public UrlAttribute()
{
ErrorMessage = "URLに利用できない文字が含まれています。";
}
private readonly char[] INVALID_CHARS =
"\\\"'|*`^><)(}{][#%;/?:@&=+$,.".ToCharArray();
public IEnumerable<ModelClientValidationRule>
GetClientValidationRules(
ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ValidationType = "url",
ErrorMessage = FormatErrorMessage(
metadata.GetDisplayName()),
};
yield return rule;
}
public override bool IsValid(object value)
{
if (value == null || value.GetType() != typeof(string))
{
return true;
}
return !(INVALID_CHARS.Any(
c => ((string)value).Contains(c)));
}
}
モデル側で適当なメンバーに[Url]を付与する。
public class Post
{
[Required]
public int PostId { get; set; }
[Required]
[Url]
[DisplayName("タイトル")]
public string Title { get; set; }
:
:
