Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 3 DataAnnotations: Not allow HTML

Is there anyway to use DataAnnotations in MVC 3 to not allow HTML is used in a textbox? I see a way to allow using HTML (AllowHTMLAttribute) but what if i dont want the user to type any HTML in the textbox and want to warning him?

Thanks :)

like image 786
Hieu Nguyen Trung Avatar asked Dec 10 '25 20:12

Hieu Nguyen Trung


1 Answers

You have to write a custom RegularExpressionAttribute ... something like this:

public class DisallowHTMLAttribute : RegularExpressionAttribute
{
    public DisallowHTMLAttribute()
        : base(@"</?\w+((\s+\w+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)+\s*|\s*)/?>")
    {
    }

    public override string FormatErrorMessage(string name)
    {

        return String.Format("The field {0} cannot contain html tags", name);

    }
}

You must register the adapter to enable client side validation, so in Application_Start in Global.asax add this line of code:

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(DisallowHTMLAttribute), typeof(RegularExpressionAttributeAdapter));

And in your model, add the attribute to the properties you want to disallow html tags, like this:

[DisallowHTML]
public string SomeProperty{ get; set; }
like image 165
Mehmetali Shaqiri Avatar answered Dec 12 '25 10:12

Mehmetali Shaqiri