How can I style invalid text field content in Spri

2020-08-01 04:37发布

问题:

The Spring MVC JSP tag library has a tag for rendering form errors. This makes it easy to render an error message next to, say, an input text field. However, it is common practice on many websites to also style the input text field itself (with a red border maybe) to highlight a validation error.

Is there any way of doing this with the Spring JSP tags or will I have to bake my own solution?

回答1:

I have never used Spring MVC JSP tags but looking at the documentation it looks like cssErrorClass is the way to go:

<form:input path="userName" cssErrorClass="error"/>

Equivalent to "class" - HTML Optional Attribute. Used when the bound field has errors.

Obviously you can now define input.error class in your CSS stylesheet.



回答2:

You can use spring:bind tag around the form:input tag. In between the spring:bind tag you can use something like ${status.error ? 'error' : ''} for your style class.

status.error will be true if errors. form input field is available