Search code examples
ajaxjsfrichfacesvalidation

jsf inputText validator


Is there a way in richfaces ajaxvalidator or ajax suport a user from writting in an inputText to as soon as he writes something other than a number. In other words is it possible to disable the inputText field when the user inputs NaN.

for example: if the user tries to write : "11a" , is there a way to prevent the user from writting the a? so when he presses the "a" a warning that input is not a number will appear.

This is the jsf code:

<h:inputText id="price" value="#{carBB.price}" required="true">
    <rich:ajaxValidator event="onkeypress"/>                
</h:inputText>

This is in the bean code:

@NotNull
private double price;

public double getPrice() {
return price;
}

public void setPrice(int price) {
this.price = price;
}

In my code the warning appears when the user writes NaN but that doesn't prevent him from writing it.


Solution

  • I ended up with this that worked fine for me only allows doubles:\

    In header:

    <script type="text/javascript">
    function disableKeys(e,exist)
    {
        var unicode=e.keyCode;
        var value = exist.value;
        if((unicode< 0x30 && unicode != 0x2E) || unicode> 0x39) 
        {
            alert("Invalid Input should be number or \".\"");
            return false;
        }
        else if(unicode == 0x2E && value.indexOf(".")>=0)
        {
            alert("Invalid Input already contains a \".\"");
            return false;
        }
        else
        {
            return true;
        }
    
    }
    </script>
    

    In body:

    <h:inputText id="price" value="#{carBB.price}" onkeypress="return disableKeys(event,this);"/>