c# - How Can I Use Data Annotations Attribute Classes to Fail Empty Strings in Forms? -


i trying require text input field in form, implies there needs in form. however, adding [required] tag model wasn't working. specifically, @ user name property:

public class columnwidthmetadata {     [displayname("column name")]     [required]     public string colname { get; set; }      [displayname("primary key")]     public int pkey { get; set; }      [displayname("user name")]     [required]     public string username { get; set; }      [displayname("column width")]     [required]     public int width { get; set; } } 

this allows empty strings past model validation , database error thrown when attempts insert null value user name.

how can change these attributes seem should do?

after lot of googling , looking on stackoverflow, had nothing.

i went msdn , looked @ system.componentmodel.dataannotations namespace.

there looked more closely @ required attribute, , noticed allowemptystrings property. setting false tells attribute not allow empty strings, have assumed default behavior, seeing how point of required require entered, , empty string indicates nothing entered.

this doesn't solve problem though, default empty strings coerced null, not empty strings, , therefore allowed. once again absurd, required supposed test if entered, , null indicates nothing entered. however, allowemptystrings page has link displayformattribute's property convertemptystringstonull. if set false, empty strings remain empty strings, , required tag not allow them.

so, here's fix:

public class columnwidthmetadata {     [displayname("column name")]     [required(allowemptystrings=false)]     [displayformat(convertemptystringtonull=false)]     public string colname { get; set; }      [displayname("primary key")]     public int pkey { get; set; }      [displayname("user name")]     [required(allowemptystrings=false)]     [displayformat(convertemptystringtonull=false)]     public string username { get; set; }      [displayname("column width")]     [required]     public int width { get; set; } }     

Comments

Popular posts from this blog

php - render data via PDO::FETCH_FUNC vs loop -

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

The canvas has been tainted by cross-origin data in chrome only -