gpt4 book ai didi

javascript - 无法调用 JS 进行验证 (JSF)

转载 作者:行者123 更新时间:2023-11-30 13:10:31 25 4
gpt4 key购买 nike

当用户按下提交时,我无法让它调用下面的 JS,我错过了什么

<script type="text/javascript"> 

function required(){
if (document.getElementById("Username").value.length == 0)
{
alert("message");
return false;
}
return true;
}

</script>

用户输入用户名的代码

<h:form> <!--onsubmit="return username_validation();">-->


<h:outputLabel for="username">Please enter your username: </h:outputLabel>
<h:inputText id="Username" label="Username" value="#{user.id}"
size="20" required="true" requiredMessage="Please enter a username" >
<f:ajax event="blur" render="usernameMessage" />
</h:inputText><br></br><br></br>
<h:message id="usernameMessage" for="username" />
To print a piece of text, please press the submit button below to upload the text:<br/><br/>
<h:commandButton type="Submit" value="Submit" onclick="return username_validation()" action="upload/uploadText" styleClass="submit"/>

</h:form>

感谢你们的帮助,我现在有了以下内容:但是我永远无法得到 h:inputText 旁边的错误消息我该怎么做?

 <h:form> <!--onsubmit="return username_validation();">-->


<h:outputLabel for="username">Please enter your username: </h:outputLabel>
<h:inputText id="Username" label="Username" value="#{user.id}"
size="20" required="true" requiredMessage="Please enter a username" >

</h:inputText><br></br><br></br>

To print a piece of text, please press the submit button below to upload the text:<br/><br/>
<h:commandButton type="Submit" value="Submit" onclick="return username_validation()" action="upload/uploadText" styleClass="submit"/>

</h:form>

这也是我的 userBean,我已经添加了 @NotNull,但这目前不起作用,我是不是漏掉了什么?

package com.corejsf;

import java.io.Serializable;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.validation.constraints.NotNull;


@Named("user")
@SessionScoped
public class UserBean implements Serializable {

@NotNull(message = "Please enter a username")
private String id;

public String getId() {
return id;
}

public void setId(String newValue) {
id = newValue;
}
private String fileText;

public String getFileText() {
return fileText;
}

public void setFileText(String fileText) {
this.fileText = fileText;
}
}

最佳答案

查看生成的 HTML 源代码。在浏览器中右键单击页面并执行查看源代码。在 HTML 源代码中根本不存在 ID 为 Username 的元素。相应地修复它。

<h:form id="form" ...>
<h:inputText id="username" ... />
    ...
</h:form>

var usernameElement = document.getElementById("form:username");

与具体问题无关,您正朝着错误的方向纯粹通过 JavaScript 执行验证。这是不可靠的。只需使用 required="true"

<h:form>
<h:inputText id="username" ... required="true">
<f:ajax event="blur" render="usernameMessage" />
</h:inputText>
<h:message id="usernameMessage" for="username" />
...
</h:form>

另见:

关于javascript - 无法调用 JS 进行验证 (JSF),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14024817/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com