简体   繁体   中英

jQuery empty validation for primefaces components

I am wonder how to check by jQuery if there are some fields empty. If yes I'll show a dialog.

I was trying something like:

$('input:text').each(function( index ) {    
    if( $(this).val().length == 0){ 
         ...
    } 
});

Unfortunately I saw that for example for <p:selectOneMenu> value is always "" , or what about p:selectOneRadio ?

Each component in PrimeFaces has it's own way to check if the value is empty or not.

Taking that in mind I'll post how to check for empty values in inputText, selectOneMenu, selectOneRadio in "almost" generic way.

for (var propertyName in PrimeFaces.widgets) {
   if (PrimeFaces.widgets[propertyName] instanceof PrimeFaces.widget.InputText) {
      if(PrimeFaces.widgets[propertyName].jq.val().length == 0) {
         PrimeFaces.widgets[propertyName].jq.css('background', 'red')
      } 
    } else if(PrimeFaces.widgets[propertyName] instanceof PrimeFaces.widget.SelectOneRadio) {
      if(PrimeFaces.widgets[propertyName].checkedRadio.length == 0){
         PrimeFaces.widgets[propertyName].jq.css('background', 'red')
       }                                 
    } else if(PrimeFaces.widgets[propertyName] instanceof  PrimeFaces.widget.SelectOneMenu) {
      if(PrimeFaces.widgets[propertyName].getSelectedValue() == '') {
         PrimeFaces.widgets[propertyName].jq.parent().css('background', 'red')
      } 
    }
}

Basically we iterate over the widgets of PrimeFaces that we have in the page, and determine the way on how we check the value based on the component's type.

Now to extend this, you need to write every individual component's way of validation.

A small working example can be found on github . And an online Demo .

Hope this helps.

Maybe something like that:

$('input:text').each(function( index ) {    
     if( $(this).val().length == 0 || $.trim($(this).val()) == ""){ 
         alert("empty");
     } 
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM