Reputation: 6563
I use jsf form with a few inputs. Some inputs are required. I check on an empty space through required="true". But i need to check before submit form if user just typed a few gaps space-key from keyboard, cause then the value is stored in the database, but I don't need it. I thought it may be implement using jQuery method trim(), but I'm a new to jQuery and I have no idea how to implement it.
<h:form prependId="false">
<div class="row">
<div class="col-lg-3 form-group">
<label>First Name<span class="text-danger"> *</span></label>
<h:inputText value="#{userController.user.firstName}"
styleClass="form-control" id="firstName"
required="true" requiredMessage="#{bundle.common_error_empty_value}"/>
<h:message for="firstName" styleClass="validationMsg"></h:message>
</div>
<div class="col-lg-5 form-group">
<label>Last Name:<span class="text-danger"> *</span></label>
<h:inputText value="#{userController.user.lastName}"
styleClass="form-control" id="lastName"
required="true" requiredMessage="#{bundle.common_error_empty_value}"/>
<h:message for="lastName" styleClass="validationMsg"></h:message>
</div>
</div>
//etc...
</h:form>
I tried something like this. Maybe someone have an idea how I can check fields on white spaces.
<script type="text/javascript">
function trimInputs() {
$('form input').each(function () {
$.trim(value);
});
}
</script>
Upvotes: 2
Views: 10348
Reputation: 31651
If you use Hibernate validators then it could go with @mabi's solution, which is also explained here. Otherwise, you could also write your own JSF validator:
@FacesValidator
public class NoBlankSpaceValidator implements Validator{
@Override
public void validate(FacesContext context, UIComponent component,
Object value) throws ValidatorException {
//Check if user has typed only blank spaces
if(value.toString().trim().isEmpty()){
FacesMessage msg =
new FacesMessage("Incorrect input provided",
"The input must provide some meaningful character");
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ValidatorException(msg);
}
}
}
And use it as:
<h:inputText value="#{userController.user.firstName}"
required="true" requiredMessage="#{bundle.common_error_empty_value}"
validator="noBlankSpaceValidator"/>
See also:
Upvotes: 7
Reputation: 1456
You could do this the old fashioned way:
<h:inputText id="lastName"
onchange="this.value = this.value.trim()"
/>
And add whatever validations you want. The onchange fires before the validations do, so it will act as if the user did not enter any spaces at the beginning or end of the input.
Upvotes: 4
Reputation: 5307
From your "save to the DB" bit, maybe adding a @NotBlank
constraint to the corresponding field is all that you need.
See this this answer for an example.
Upvotes: 0