Accept only digits for h:inputText value

2019-01-17 22:44发布

Is there a way to confirm the value of an h:inputText in JSF, which should accepts only digits. Means it can be an Integer or the float.

If I type 12s3a562.675 , a5678s12 , 68712haf.563345 or any other such kind of values, then it should show an error. Otherwise it accepts and proceeds.

10条回答
我欲成王,谁敢阻挡
2楼-- · 2019-01-17 23:24

You can use a JS validation

First, you need to define a JS function to validate the input

function validateInput(regexString) {
    var theEvent = window.event || event;
    var key = theEvent.keyCode || theEvent.which;
    if (key >= 46) {
        key = String.fromCharCode(key);
        var regex = new RegExp("^" + regexString + "$");
        if (!regex.test(key)) {
            theEvent.returnValue = false;
            if (theEvent.preventDefault) {
                theEvent.preventDefault();
            }
        }
    }
}

Second, in your h:input, capture the onKeyPress event and call the function

<h:inputText value="..." onKeyPress="validateInput('[0-9]*')/>

And it will only let you enter numbers.

You can easily extend this use to other case when you need to validate whit other regex.

Note, this only work with key press, if you want to capture other user event, use the proper tag.

Cheers

查看更多
叛逆
3楼-- · 2019-01-17 23:26

This is working for me

onkeypress="if( (event.which &lt; 48 || event.which &gt; 57) ) return false;"
查看更多
虎瘦雄心在
4楼-- · 2019-01-17 23:28

Just bind the input value to a Double, or better, BigDecimal property instead of String.

private BigDecimal number; // Double can also, but beware floating-point-gui.de
<h:inputText value="#{bean.number}" />

JSF has builtin converters for those types which will kick in automatically. You can customize the converter message as below:

<h:inputText value="#{bean.number}" converterMessage="Please enter digits only." />
查看更多
太酷不给撩
5楼-- · 2019-01-17 23:37

A html5, cross browser and client side solution could be

<script>
  //<![CDATA[   
  $(document).ready(function(){
    $("#someinputid\\:withcolon").attr('type', 'number');
  });
  //]]>
</script>
  • For firefox this enables info bubbles to advice the user to input valid numbers before submitting
  • For IE it submits immediately, clears the input widget, resets to zero (if input is invalid), doesn't give the user a chance to correct on client side, but ensures a valid server request
  • For chrome not tested

you need to reference a jquery resource if not implicitly available by e.g. prime faces

查看更多
登录 后发表回答