JSF, validateRegex and & (ampersand)

2020-02-15 02:45发布

I want to test inputText field to see if its content matches anything but at least one & (ampersand).

When I test & or \& or \\& inside pattern field of validateRegex, I always received this error :

javax.faces.view.facelets.FaceletException: Error Parsing /index.xhtml: Error Traced[line: 71] Le nom de l'identité doit immédiatement suivre le caractère "&" dans la référence d'entité.

and I get 500 error...

How can I escape this character?


Update

I have tested

<p:inputText id="player_name_register" value="#{login.name}">
    <f:validateRegex pattern="[&amp;]{3, 50}" />
</p:inputText>

But when I test with &&&&&& it doesn't work.

I also tested

<![CDATA[
    <p:inputText id="player_name_register" value="#{login.name}">
        <f:validateRegex pattern="[&amp;]{3, 50}" />
    </p:inputText>
]]>

but my inputText doesn't appear anymore.

标签: java regex jsf
3条回答
家丑人穷心不美
2楼-- · 2020-02-15 03:27

Facelets is a XML based view technology. The whole view has to be syntactically valid XML. XML special characters like &, < and > needs to be escaped as &amp;, &lt; and &gt; when they're supposed to be interpreted as-is.

<f:validateRegex pattern="...&amp;..." />

(here, the ... represents the remainder of your regex)

A CDATA block won't work as it basically escapes the entire content, including JSF components. Quoting the escaped XML character makes no sense. After being parsed by the Facelets XML parser, the &amp; becomes & again.


Update as per your update, the space in {3, 50} is causing the regex syntax error. Remove it.

<p:inputText id="player_name_register" value="#{login.name}">
    <f:validateRegex pattern="[&amp;]{3,50}" />
</p:inputText>

Using CDATA blocks around the JSF component is not the right solution at all. It would XML-escape the entire content, resulting in &lt;p:inputText&gt; being emitted plain vanilla instead of the component's HTML representation.

查看更多
戒情不戒烟
3楼-- · 2020-02-15 03:37

Use the CDATA tag to escape the ampersand (&) symbol:

<![CDATA[
<h:outputText value="Sun & Moon" />
]]>

If you want to escape ampersand, lt (<) and gt (>) symbols in Javascript, add the CDATA section in Javascript but comment it:

<script>
    //<![CDATA[
    funcion lessThan(a, b) {
        return a < b; //no problems in Facelets
    }
    //]]>
</script>
查看更多
唯我独甜
4楼-- · 2020-02-15 03:47

Does a quoted string check help ? '&amp;'

查看更多
登录 后发表回答