0

I am creating web application using JSF 2.0 where I am doing validation for full name.

<h:inputText value="#{PersonalInformationDataBean.fullName}" size="75" id="fullName" >
     <f:validator validatorId="fullNameValidator" />
</h:inputText>
<font color="red"><br /><h:message for="fullName"/></font>

In java below is what I have

public class FullNameValidator implements Validator {

    public void validate(FacesContext context, UIComponent component, Object value)
            throws ValidatorException {

        String enteredName = (String) value;
        // Pattern p = Pattern.compile("([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)");
        Pattern p = Pattern.compile("([a-zA-Z\\s]+)");
        Matcher m = p.matcher(enteredName.trim());
        System.out.println("trimmed data is " + enteredName.trim());
        boolean matchFound = m.matches();

        if (enteredName.trim().length() == 0) {
            FacesMessage message = new FacesMessage();
            message.setSummary("Please enter name.");
            throw new ValidatorException(message);
        }

        if (enteredName.trim().length() < 10) {
            FacesMessage message = new FacesMessage();
            message.setSummary("Name should be atleast 10 characters.");
            throw new ValidatorException(message);
        }

        if (!matchFound) {
            FacesMessage message = new FacesMessage();
            message.setSummary("Invalid Name.");
            throw new ValidatorException(message);
        }

//        FacesMessage message = new FacesMessage();
//        message.setSummary("");
//        throw new ValidatorException(message);

    }
}

When I run project locally, it runs perfectly.

When I took this project online, I am facing problem.

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+ fullName data as        +   Error Message                      +
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+ 123343543534545         +   Invalid Name                       +
+ fahim                   +   Full name should be 10 characters  +
+ null (blank)            +   NO MESSAGE, here I was expecting   +
+                         +   result as Please enter name        +
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

I don't understand when I don't pass any value, why I don't get error message saying Please enter name. Any idea what I am missing here?

Note:

I don't even get trimmed data is in catalina.out file where I get all message which I have printed under System.out.println

The problem is when I pass data at that time only validation is called. Else validation is not happening. Please let me know what I am missing here.

Fahim Parkar
  • 30,974
  • 45
  • 160
  • 276
  • why don't you use `required="true"` in your `h:inputText` – Daniel Sep 02 '12 at 12:13
  • @Daniel : If I keep required="true", I get default error as "fullName: Validation Error: Value is required." which I don't want. I want my own messages. – Fahim Parkar Sep 02 '12 at 12:18
  • than you can use `requiredMessage=""` in your `h:inputText` or override the JSF default message for required field validation (`javax.faces.component.UIInput.REQUIRED`) http://www.mkyong.com/jsf2/customize-validation-error-message-in-jsf-2-0/ – Daniel Sep 02 '12 at 12:24
  • @Daniel : Nice trick for my problem. But problem is for how many pages should I write like this? Each page have atleast 10 fields. Isn't there any other way? on localhost it is working perfectly... – Fahim Parkar Sep 02 '12 at 12:36
  • @Daniel : Well locally I am using netbean and glassfish.. while uploading i m using tomcat. what I think I would need to upload jsf jar files in tomcat lib folder to get it worked... jsf-api-2.x.jar, http://www.mkyong.com/jsf2/customize-validation-error-message-in-jsf-2-0/ – Fahim Parkar Sep 02 '12 at 12:38
  • @Daniel : I am asking as earlier I got some core error, there I added jstl.jar file and it worked. – Fahim Parkar Sep 02 '12 at 12:39
  • @Daniel : Any idea how to get this done? – Fahim Parkar Sep 02 '12 at 13:06
  • @Daniel : I also kept jsf jar files inside WEB-INF/lib still same problem... – Fahim Parkar Sep 02 '12 at 13:07
  • your current problem is that the validator not being called for empty field? you placed println inside the validator and its not being printed at all for empty input? dunno maybe set javax.faces.VALIDATE_EMPTY_FIELDS context parameter in your web.xml, to true? b.t.w if you follow mkyong.com/jsf2/customize-validation-error-message-in-jsf-2-0 you will set 1 message for all required validator in one place (although it will be a general one...) – Daniel Sep 02 '12 at 13:19
  • @Daniel : When I run this locally (localhost) it runs fine, it gives me error on empty string. However when I took it live, I got error. – Fahim Parkar Sep 02 '12 at 13:27
  • but localhost is glassfish and remote one is tomcat ? your probably got different jsf implemenations on those servers ? http://stackoverflow.com/q/9415059/617373 , make sure same jsf libs are used – Daniel Sep 02 '12 at 13:33
  • @Daniel : Let me check... I think this will solve my probem... – Fahim Parkar Sep 02 '12 at 13:38
  • @Daniel : Sad to say, I went with required="true" requiredMessage="Blah Blah" :( – Fahim Parkar Sep 02 '12 at 14:17
  • INMO you should use `javax.faces.component.UIInput.REQUIRED = Blah Blah` inside your `Messages.properties` file and add ` some.package.name.Messages ` in your faces-config.xml , jut like in that link i gave you , also , look at this http://stackoverflow.com/a/8327848/617373 (in case you want prevent blank string to pass...) – Daniel Sep 02 '12 at 14:23

3 Answers3

1

The reason for your question may be is that if you want to validate the empty values you should change you web.xml's setting, to let empty fields allowed.

  <context-param>
    <param-name>javax.faces.VALIDATE_EMPTY_FIELDS</param-name>
    <param-value>true</param-value>
  </context-param>

But this way is not suggested by authority. The jsf doc said that :

For a validator to be fully compliant with Version 2 and later of the specification, it must not fail validation on null or empty values unless it is specifically intended to address null or empty values. An application-wide is provided to allow validators designed for JSF 1.2 to work with JSF 2 and later. The javax.faces.VALIDATE_EMPTY_FIELDS must be set to false to enable this backwards compatibility behavior.]1

So as you are using jsf2.0, a another way to validate the empty value is that you can add do like this :
<h:inputText value="#{PersonalInformationDataBean.fullName}" size="75" id="fullName" required="true" requiredMessage="Please enter name." > And also make sure the web.xml' setting as follows :

<context-param>
  <param-name>javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL</param-name>
  <param-value>true</param-value>
</context-param>

But this way will accuse another unreasonable thing.When you input the name will some thing and this form is failed for this sumbit.And user delete the name field's value to blank, it will will throw Please enter name message.But the name field in page is still the pre value(not blank).
So it is a JSF bug.To fix this, you've to alter the first part of HtmlBasicRenderer#getCurrentValue(),Please take a look at this: JSF 2 - Bean Validation: validation failed -> empty values are replaced with last valid values from managed bean

Community
  • 1
  • 1
yudong
  • 96
  • 6
0

I guess you might validate if the value passed by the Validator is not empty with

StringUtils.isNotEmpty(String) 

and throw a ValidatorException before you verify it`s size.

If the field is mandatory, you may also consider using required="true"

Consider adding the following snippet of code:

String enteredName = (String) value;
// checks for null and empty String values
if ( StringUtils.isEmpty(enteredName) ) {
    FacesMessage message = new FacesMessage();
    message.setSummary("Please enter name.");
    throw new ValidatorException(message);
}
// rest of your validation code
gdfbarbosa
  • 825
  • 3
  • 10
  • 21
0

A validator is not called when no input value is entered, the idea being that there is nothing to validate. This is a bit unintuitive, but required="true" attribute should be used to check is a value is needed. There is an alternative:

<h:inputText label="Username" validatorMessage="The value entered for #{component.label} is invalid">
      <f:validateRegex pattern="[A-Za-z]{10,30}"/>
</h:inputText>

You don't need both == 0 and < 10, just < 10. Use the attribute requiredMessage to add your own message for the required attribute.

Note that you don't need to use StringUtils.isNotEmpty(String), just this:

String s;
if(s.isEmpty() {
...

Note also that the font tag was deprecated in HTML 4.01, try this:

<h:message for="fullName" style="color: red"/>
Oversteer
  • 1,778
  • 1
  • 22
  • 38
  • > this is not a problem. Please... what do you mean? – Oversteer Sep 02 '12 at 12:24
  • you don't get my question. When I am passing nothing, I should have gotten output as "trimmed data is "... YES OR NO?? I don't get this, so forget about `enteredName.trim().length() == 0` – Fahim Parkar Sep 02 '12 at 12:41
  • hope you got my problem... With CAPS I don't meant to shout... Its just for highlight... – Fahim Parkar Sep 02 '12 at 12:50
  • Are you saying that when nothing is entered, no error message is produced at all, despite the plethora of tests? have you checked that the validator is being invoked? Do you use the @FacesValidator annotation? If the validator is invoked, is the string null or not null and empty? – Oversteer Sep 02 '12 at 13:09
  • they are getting invoked ONLY when some value is passed. When no value is passed, I am not getting any error :( which is bad.. – Fahim Parkar Sep 02 '12 at 13:12
  • "they" are getting invoked?? So no error, is the validator getting called? – Oversteer Sep 02 '12 at 13:13
  • "Are you saying that when nothing is entered, no error message is produced at al" YES... no error... error only when I pass data... – Fahim Parkar Sep 02 '12 at 13:13
  • no validator is getting called... validator is only called when i have some text inside... else it don't – Fahim Parkar Sep 02 '12 at 13:14
  • Please show me the latest h:inputText and the commandButton/Link you are using to submit the form. – Oversteer Sep 02 '12 at 13:16
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/16156/discussion-between-fahim-parkar-and-oversteer) – Fahim Parkar Sep 02 '12 at 13:16
  • Hi, the validator will not be called with an empty string is submitted, this is a bit strange but it's how it works. The theory is that there's nothing to validate, because nothing was entered. This is why you have to use required=. – Oversteer Sep 02 '12 at 13:22
  • then how is it getting called when project is localhost? – Fahim Parkar Sep 02 '12 at 13:25
  • can you come in chat room so that we can discuss there? – Fahim Parkar Sep 02 '12 at 13:25
  • sorry, watching forumla 1. I'm sure there isn't any difference in behavior with localhost, maybe there's some confusion. – Oversteer Sep 02 '12 at 13:41
  • I am fan of Formula 1 too.. Who won today?? Alonso?? – Fahim Parkar Sep 02 '12 at 13:43