How to change css class for the inputfield and label when validation fails?
Bind the input component to the view via binding
attribute. It'll become available as an UIInput
component reference in EL, so that you can use UIInput#isValid()
in styleClass
attribute.
<h:outputLabel for="emailInput" value="Email"
styleClass="#{emailInput.valid ? '' : 'error'}" />
<h:inputText id="emailInput" binding="#{emailInput}" ...
styleClass="#{emailInput.valid ? '' : 'error'}" />
(note that I fixed your label to be a real label; also note that you don't need to create some bean property at all as suggested by the answer of cubbuk)
Yes, this may produce quite some non-DRY boilerplate code in the view. You can abstract this away with a phase listener or a system event listener. You can also use OmniFaces <o:highlight>
component which does all the job transparently. See also the live demo.
How to alter the client-side validation error CSS class of an input field using ASP.NET Core?
Found a simple solution! Add a CSS change listener to the input
element;
This example adds a listener to the "input" element, but could also be applied to other elements.
Taken from here jQuery - Fire event if CSS class changed
Here is my implementation, notice that I modify the CSS in the listener, which could potentially cause a stack overflow.
<script type="text/javascript">
// Create a closure
(function() {
var originalAddClassMethod = jQuery.fn.addClass;
jQuery.fn.addClass = function() {
// Execute the original method.
var result = originalAddClassMethod.apply(this, arguments);
// trigger a custom event
// stop recursion...
if ((arguments[0] != "is-valid") && (arguments[0] != "is-invalid")) {
jQuery(this).trigger('cssClassChanged');
}
// return the original result
return result;
}
})();
// document ready function
$(function() {
$("input").bind('cssClassChanged', function(){
// cleanup
if ($(this).hasClass("is-valid")) {
$(this).removeClass("is-valid");
}
if ($(this).hasClass("is-invalid")) {
$(this).removeClass("is-invalid");
}
// remap the css classes to that of BootStrap
if ($(this).hasClass("input-validation-error")) {
$(this).addClass("is-invalid");
}
if ($(this).hasClass("valid")) {
$(this).addClass("is-valid");
}
});
});
</script>
Change the CSS class of an input on validation error with razor
With MVC3, an input-validation-error
CSS class will automatically be added to to the input elements which have validation errors.
Therefore in your CSS you can style this class:
.input-validation-error
{
color:red;
}
Customizing class for element of error message only in jQuery Validation plugin
No, the plugin dynamically adds the errorClass
to both the input and the error message element and you cannot change this behavior, nor would you need to change it. After all, having classes on elements does nothing until you create some CSS properties that targets them.
So by using the correct CSS selectors, you can easily target these elements individually.
The default label
container for validation messages along with the default errorClass
setting, which is "error"
...
label.error {
/* CSS properties targeting only the error messages */
}
select.error,
textarea.error,
input[type="text"].error,
input[type="radio"].error,
input[type="checkbox"].error {
/* CSS properties targeting only the input elements */
}
DEMO: http://jsfiddle.net/j3te0d10/
Is there anyway to set class for error message element only?
You wouldn't ever need to do this.
Just target label.error
in your CSS and only the error messages are affected.
label.error {
/* CSS properties targeting only the error messages */
}
DEMO 2: http://jsfiddle.net/j3te0d10/1/
How to apply a specific style to an invalid field?
When the model validation fails and you return to the same view, the framework will add the input-validation-error
CSS class to the input elements, for which the validation failed. In your case, you are adding the error message to the UserName
field, so your UserName
field input will get this new CSS class.
<input class="form-control input-validation-error" type="text" name="username"
required="" id="UserName" value="some value">
You can add any sort of styling you want to this CSS class as needed.
.input-validation-error
{
border-color:red;
}
Now setting the focus on a specific input field is a little tricky. The server code cannot do that. You have to do that on client side. But if there are multiple fields in the form with failed validation, which one you want to focus ? The first one, second one ? last one ?
Here is a quick sample to focus on the first input element with input-validation-error
CSS class. The JavaScript code is executed on the jquery document.ready
event.
$(function () {
$("input.input-validation-error").first().focus();
});
If you want to style the validation error message rendered by the validation helper (<span asp-validation-for="UserName"></span>
), follow the same approach. When validation fails, the framework will change the CSS class of this span element to field-validation-error
(from field-validation-valid
). So all you have to do is, add the needed style definitions to that CSS class.
.field-validation-error
{
color:red;
}
Change Label Color if validation fails
I think you need to use the invalidHandler method.
var validator =$("#loginForm").validate({
rules: {
email: { required:true, email:true, emailRule: true, },
emailPass: { required:true,}
},
messages: {
email: { required:"enter email", email:"invalid email", },
emailPass:{ required:"enter password", }
},
invalidHandler: function (ev, validator) {
$('select your label').css('color', 'the new color');
}
});
Html.TextBox with css class specified conflicts with form validation css (input-validation-error)
Instead of relying on the framework to render styles at all, I went with an approach where I could apply my own css classes, while still using much of the Html.ValidationMessage() infrastructure.
Looks something like this:
<% bool emailError = !String.IsNullOrEmpty(Html.ValidationMessage("email")); %>
<div id="EmailMod" class="module <%= emailError ? "error" : String.Empty %>">
<label class="text_right">Email address</label>
<div class="input">
<input type="text" id="Email" name="Email" class="input" tabindex="1" />
<p id="EmailRequired" class="required <%= emailError ? "" : "hide" %>">* Please enter a valid email address.</p>
</div>
</div>
Changing the color of a label without js if input validation fails
CSS has general sibling combinator ~ and adjacent sibling combinator + and non of them can select previous sibling element. Therefor you gotta change the order of your elements, so the input comes first. This is one way to do it:
.form-group input:invalid+b:before {
content: "Form is invalid";
color: red;
}
input[type="text"]:invalid~label {
color: red;
}
.address {
position: relative;
padding-left: 100px;
}
.address label {
position: absolute;
left: 0;
line-height: 30px;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
<div class="form-group address">
<input type="text" id="address" name="address" pattern="^\d+\s[A-z]+\s[A-z]+,\s+[A-z]+,\s+[A-z]{2}\s+\d{5}" />
<b></b>
<label for="address" class="form-group__names" id="invalid">Address</label>
</div>
</div>
Related Topics
Dynamically Define a Variable in Less CSS
CSS Styling Won't Work in Outlook 2010
Is There Any Equivalent to Ie Conditional Comment for Chrome and Safari
Make Outer Div Be Automatically the Same Height as Its Floating Content
Textarea's Rows, and Cols Attribute in CSS
Moving Dotted Border Using CSS
Compiling Issue in Bootstrap 3 with Namespace
Adding a Small Picture on the Right Side of Textfield with CSS
Table-Cell - Some Kind of Colspan
Does IE9 Not Support Display: Inline-Flex at All