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

Javascript 无法调用JS进行验证(JSF),javascript,jsf,Javascript,Jsf,当用户按submit时,我无法让它调用下面的JS,我缺少什么 <script type="text/javascript"> function required(){ if (document.getElementById("Username").value.length == 0) { alert("message");

当用户按submit时,我无法让它调用下面的JS,我缺少什么

<script type="text/javascript"> 

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

    </script> 
这也是我的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>

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


...
另见:

呈现的HTML是什么样子的?嘿,我记得在引导中使用了一个功能:如果为输入字段指定
required
属性,则必须填充该属性。。不确定它是html5规范还是引导技巧。好的,谢谢,我会研究它,呈现的HTML看起来很好没有错误,当我按submit时,它会将用户带到下一页而不会出现错误谢谢那些教程很棒,我有两个快速问题,我的错误消息从未出现在
I mixed
render
属性的侧面,我更新了答案。至于
@NotNull
,只有当JSF被配置为将空提交值解释为null时,这才有效。这也包含在链接教程中。谢谢我现在将重新阅读它,我也更新了我的代码,但仍然在用户名所在的正文上方收到错误消息,有什么想法吗?你的教程很棒!,刚刚成功地完成了not null
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;
    }
}
<h:form id="form" ...>
    <h:inputText id="username" ... />
    ...
</h:form>
var usernameElement = document.getElementById("form:username");
<h:form>
    <h:inputText id="username" ... required="true">
        <f:ajax event="blur" render="usernameMessage" />
    </h:inputText>
    <h:message id="usernameMessage" for="username" />
    ...
</h:form>