I create some helper method and create TextBoxFor inside it.
input.AppendLine(html.TextBoxFor(expression, format, attributes).ToString());
My format was "{0:dd/MM/yyyy}". It's work totally fine and render as
<input class="form-control req" data-val="true" data-val-date="The field detr must be a date." id="detr" name="detr" type="text" value="25/05/2558" />
But when ModelState has error on this field, TextBoxFor was totally ignore my format and rendered as
<input class="input-validation-error form-control req" data-val="true" data-val-date="The field detr must be a date." id="detr" name="detr" type="text" value="28/5/2558 0:00:00" />
What happened here?
How can I fixed this?
Thank you in advance.
I finally found source of this strange phenomenon.
It's happend when i use FluentValidator and explicitly call
validator.validate(obj)
When i add it's into ModelState, ModelState's property RawValue data type was DateTime. and that mess everything up. (if not explicitly call but set validator as class attribute RawValue data type will be string)
So I found 2 ways to fix this problem.
1st: Just set validator as class attribute and not explicitly call validator.
[FluentValidation.Attributes.Validator(typeof(objValidator))]
2nd: Create new ModelState and manually add model error.
var _validator = new ObjValidator();
var results = _validator.Validate(dto);
ModelStateDictionary modelStateDicts = new ModelStateDictionary();
foreach (KeyValuePair<string, ModelState> kv in ModelState.Where(x => results.Errors.Count(y => y.PropertyName == x.Key) > 0))
{
modelStateDicts.AddModelError(kv.Key, results.Errors.FirstOrDefault(x=>x.PropertyName == kv.Key).ErrorMessage);
}