基於@Avitus建議: 這就是我做了基於預定義的配置,使HTML元素動態驗證: 1.我在DB ScreenElement創建了兩個表,ScreenSettings:
CREATE TABLE [HR].[ScreenElement](
[Id] [int] IDENTITY(1,1) NOT NULL,
[ElementId] [nvarchar](50) NULL,
[ElementName] [nvarchar](50) NULL,
[ScreenId] [int] NULL,
[IsRequired] [bit] NULL,
[MinLength] [int] NULL,
[MaxLength] [int] NULL,
CONSTRAINT [PK_ScreenElement] PRIMARY KEY CLUSTERED (
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE TABLE [HR].[ScreenSettings](
[Id] [int] IDENTITY(1,1) NOT NULL,
[NameA] [nvarchar](50) NULL,
[NameL] [varchar](50) NULL,
[ScreenKey] [varchar](150) NULL,
CONSTRAINT [PK_ScreenSettings] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
2.I通過屏幕關鍵字獲取配置ControllerName.ActionName
並在屏幕加載時將其傳遞到ViewBag中,然後將其序列化爲js對象。 3.文檔準備就緒。我用data-x
屬性和一些樣式類標記元素。
var screenConfig = @Html.Raw(new JavaScriptSerializer().Serialize(ViewBag.ScreenConfig));
$(document).ready(function() {
_.each(screenConfig, function(value, key) {
if (value.IsRequired == true) {
$("#"+value.ElementId).attr("required", "required");
$("#"+value.ElementId).addClass("required-input");
}
if (value.MinLength !== 0 && value.MaxLength !== 0&&value.MaxLength>=value.MinLength) {
$("#"+value.ElementId).attr("data-min", value.MinLength.toString());
$("#"+value.ElementId).attr("data-max", value.MaxLength.toString());
if (value.MinLength === value.MaxLength) {
$("#"+value.ElementId).attr("data-length", value.MinLength.toString());
}
}
});});
就是這樣。
我認爲你正在尋找的HTML輸入屬性['maxlength'(https://www.w3schools.com/html/html_form_attributes.asp)? – Gareth
@Gareth'maxLength'會限制最大值,OK,但我需要的是強制一個特定的長度。 –