|
|
|
JSF валидация проверка на обязательность
|
|||
|---|---|---|---|
|
#18+
Есть такой вот вопрос: возможно ли в JSF настроить проверку на обязательность сразу для группы полей, т.е я хочу, чтобы в группе из нескольких полей валидация не проходила, если не заполнено хотя бы одно из этих полей. Мб у кого-нить есть полезная ссылка или (лучше всего) пример кода? Заранее благодарен ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 12.04.2007, 15:16:39 |
|
||
|
JSF валидация проверка на обязательность
|
|||
|---|---|---|---|
|
#18+
Так а чем не подходит установка в каждом обязятельном для заполнения поле атрибута - required="true" ? ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 12.04.2007, 15:24:53 |
|
||
|
JSF валидация проверка на обязательность
|
|||
|---|---|---|---|
|
#18+
Пример есть в книге Core JSF Хорстманна и Гери. Глава 6 -Validating Relationships Between Multiple Components The validation mechanism in JSF was designed to validate a single component. However, in practice, you often need to ensure that related components have reasonable values before letting the values propagate into the model. For example, as we noted earlier, it is not a good idea to ask users to enter a date into a single textfield. Instead, you would use three different textfields, for the day, month, and year, as in Figure 6-11. If the user enters an illegal date, such as February 30, you would like to show a validation error and prevent the illegal data from entering the model. The trick is to attach the validator to the last of the components. By the time its validator is called, the preceding components passed validation and had their local values set. The last component has passed conversion, and the converted value is passed as the Object parameter of the validation method. Of course, you need to have access to the other components. You can easily achieve that access by using a backing bean that contains all components of the current form (see Listing 6-16). Simply attach the validation method to the backing bean: public class BackingBean { private UIInput dayInput; private UIInput monthInput; ... public void validateDate(FacesContext context, UIComponent component, Object value) { int d = ((Integer) dayInput.getLocalValue()).intValue(); int m = ((Integer) monthInput.getLocalValue()).intValue(); int y = ((Integer) value).intValue(); if (!isValidDate(d, m, y)) { FacesMessage message = ...; throw new ValidatorException(message); } } ... } Note that the value lookup is a bit asymmetric. The last component does not yet have the local value set since it has not passed validation. Figure 6-12 shows the application's directory structure. Listing 6-17 shows the JSF page. Note the converter property of the last input field. Also note the use of the binding attributes that bind the input components to the backing bean. Listing 6-16. validator3/WEB-INF/classes/com/corejsf/BackingBean.java 1. package com.corejsf; 2. 3. import javax.faces.application.FacesMessage; 4. import javax.faces.component.UIComponent; 5. import javax.faces.component.UIInput; 6. import javax.faces.context.FacesContext; 7. import javax.faces.validator.ValidatorException; 8. 9. public class BackingBean { 10. private int day; 11. private int month; 12. private int year; 13. private UIInput dayInput; 14. private UIInput monthInput; 15. private UIInput yearInput; 16. 17. // PROPERTY: day 18. public int getDay() { return day; } 19. public void setDay(int newValue) { day = newValue; } 20. 21. // PROPERTY: month 22. public int getMonth() { return month; } 23. public void setMonth(int newValue) { month = newValue; } 24. 25. // PROPERTY: year 26. public int getYear() { return year; } 27. public void setYear(int newValue) { year = newValue; } 28. 29. // PROPERTY: dayInput 30. public UIInput getDayInput() { return dayInput; } 31. public void setDayInput(UIInput newValue) { dayInput = newValue; } 32. 33. // PROPERTY: monthInput 34. public UIInput getMonthInput() { return monthInput; } 35. public void setMonthInput(UIInput newValue) { monthInput = newValue; } 36. 37. // PROPERTY: yearInput 38. public UIInput getYearInput() { return yearInput; } 39. public void setYearInput(UIInput newValue) { yearInput = newValue; } 40. 41. public void validateDate(FacesContext context, UIComponent component, 42. Object value) { 43. int d = ((Integer) dayInput.getLocalValue()).intValue(); 44. int m = ((Integer) monthInput.getLocalValue()).intValue(); 45. int y = ((Integer) value).intValue(); 46. 47. if (!isValidDate(d, m, y)) { 48. FacesMessage message 49. = com.corejsf.util.Messages.getMessage( 50. "com.corejsf.messages", "invalidDate", null); 51. message.setSeverity(FacesMessage.SEVERITY_ERROR); 52. throw new ValidatorException(message); 53. } 54. } 55. 56. private static boolean isValidDate(int d, int m, int y) { 57. if (d < 1 || m < 1 || m > 12) return false; 58. if (m == 2) { 59. if (isLeapYear(y)) return d <= 29; 60. else return d <= 28; 61. } 62. else if (m == 4 || m == 6 || m == 9 || m == 11) 63. return d <= 30; 64. else 65. return d <= 31; 66. } 67. 68. private static boolean isLeapYear(int y) { 69. return y % 4 == 0 && (y % 400 == 0 || y % 100 != 0); 70. } 71. } Listing 6-17. validator3/index.jsp 1. <html> 2. <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> 3. <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> 4. <f:view> 5. <head> 6. <link href="styles.css" rel="stylesheet" type="text/css"/> 7. <f:loadBundle basename="com.corejsf.messages" var="msgs"/> 8. <title><h:outputText value="#{msgs.title}"/></title> 9. </head> 10. <body> 11. <h:form> 12. <h1><h:outputText value="#{msgs.enterDate}"/></h1> 13. <h:panelGrid columns="3"> 14. <h:outputText value="#{msgs.day}"/> 15. <h:inputText value="#{bb.day}" binding="#{bb.dayInput}" 16. size="2" required="true"/> 17. <h:panelGroup/> 18. 19. <h:outputText value="#{msgs.month}"/> 20. <h:inputText value="#{bb.month}" binding="#{bb.monthInput}" 21. size="2" required="true"/> 22. <h:panelGroup/> 23. 24. <h:outputText value="#{msgs.year}"/> 25. <h:inputText value="#{bb.year}" 26. binding="#{bb.yearInput}" size="4" required="true" 27. validator="#{bb.validateDate}"/> 28. <h:message for="year" styleClass="errorMessage"/> 29. </h:panelGrid> 30. <h:commandButton value="#{msgs.submit}" action="submit"/> 31. </h:form> 32. </body> 33. </f:view> 34. </html> An alternative approach is to attach the validator to a hidden input field that comes after all other fields on the form. <h:inputHidden validator="#{bb.validateDate}" value="needed"/> The hidden field is rendered as a hidden HTML input field. When the field value is posted back, the validator kicks in. (It is essential that you supply some field value. Otherwise, the component value is never updated.) With this approach, the validation function is more symmetrical since all other form components already have their local values set. NOTE It would actually be worthwhile to write a custom date component that renders three input fields and has a single value of type Date. That single component could then be validated easily. However, the technique of this section is useful for any form that needs validation across fields. ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 12.04.2007, 17:33:15 |
|
||
|
JSF валидация проверка на обязательность
|
|||
|---|---|---|---|
|
#18+
wessenТак а чем не подходит установка в каждом обязятельном для заполнения поле атрибута - required="true" ? Тем, что мне нужно, чтобы хотя бы одно из полей этой группы было заполнено, не важно какое именно crazytoo... Спасибо, буду разбираться ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 13.04.2007, 09:20:33 |
|
||
|
|

start [/forum/topic.php?fid=59&fpage=647&tid=2146069]: |
0ms |
get settings: |
19ms |
get forum list: |
18ms |
check forum access: |
7ms |
check topic access: |
7ms |
track hit: |
56ms |
get topic data: |
20ms |
get forum data: |
6ms |
get page messages: |
95ms |
get tp. blocked users: |
2ms |
| others: | 305ms |
| total: | 535ms |

| 0 / 0 |
