Invalid & validation attributes for string applied to <select> causing client side validation issues
- Dominant language
- C#
- Stars
- 38.4k
- Forks
- 10.9k
- Avg merge
- 2d 6h
- Merged PRs (30d)
- 290
Description
### Is there an existing issue for this?
- [x] I have searched the existing issues
### Describe the bug
`data-*` attributes, and even invalid `type="text"`, `value`, `maxlength` are wrongly applied to razor form element when a `` is used.
Given following string property:
```cs
[Display(Name = Fields.Country)]
[StringLength(2, ErrorMessage = Messages.StringLength, MinimumLength = 2)]
[Required(ErrorMessage = Messages.RequiredField)]
public string CountryCode { get; set; } = "NO";// Alpha-2 code: https://en.wikipedia.org/wiki/List_of_ISO_3166_country_codes
```
With the following razor (.cshtml) code, notice no use of `asp-items=` here, also notice `` inner html is not valid, however value is:
```cshtml
π³π΄
πΈπͺ
π©π°
π©πͺ
π³π±
π§πͺ
```
Generated, with invalid (value, maxlength, type) and questionable (data-*) attributes:
```html
π³π΄
πΈπͺ
π©π°
π©πͺ
π³π±
π§πͺ
```
---
It works if you specify values via asp-items, but for the wrong reasons:
```cshtml
@{
List Countries = new List
{
new SelectListItem { Value = "NO", Text = "π³π΄", Selected = true },
new SelectListItem { Value = "SE", Text = "πΈπͺ" },
new SelectListItem { Value = "DK", Text = "π©π°" },
new SelectListItem { Value = "DE", Text = "π©πͺ" },
new SelectListItem { Value = "NL", Text = "π³π±" },
new SelectListItem { Value = "BE", Text = "π§πͺ" },
// (FI, FR, AT, CH, PL ...)
};
}
```
Generated, in this case emoji is encoded, so innerhtml now has 2 character entities, making it validate (for the wrong reasons):
```html
π³π΄
πΈπͺ
π©π°
π©πͺ
π³π±
π§πͺ
```
---
**Result** of the original case is that this is marked as invalid, and form is impossible to send.
**Workaround**:
- Add `data-val="false"` to select, so `jquery-validation-unobtrusive` opts out of validating the element.
- Or specify `asp-items` and hope all innerhtml values encodes to 2 character entities.
*Side: Validation without jQuery soon?*
### Expected Behavior
1. Not generate invalid attributes on `select`, possible tricking up jquery-validation/jquery-validation-unobtrusive
2. Perhaps `jquery-validation-unobtrusive` issue: Correctly handle `data-val-lenght*` properties on `select` element, it should validate value and not innerhtml.
### Steps To Reproduce
See above.
### Exceptions (if any)
_No response_
### .NET Version
9.0.300
### Anything else?
jquery 3.7.1
jquery-validation-1.21.0
jquery-validation-unobtrusive-3.2.11
Contributor guide
Assessment
This issue has not been assessed yet.