dotnet / dotnet/aspnetcore

Invalid & validation attributes for string applied to <select> causing client side validation issues

Open
#62,465 0 comments 0 reactions 0 assignees View on GitHub
area-ui-rendering
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

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.