Search code examples
w2ui

How to add custom validation on w2ui?


I've two fields ReasonDate and RegistrationDate. According to business logic RegistrationDate cannot be earlier than ReasonDate. I'm checking in 'onValidate' event handler of form like this:

onValidate: function(event) {
    var pattern = /(\d{2})\.(\d{2})\.(\d{4})/;
    var reasonDt = new Date(w2ui.form.record.ReasonDate.replace(pattern, '$3-$2-$1'));
    var registrationDt = new Date(w2ui.form.record.RegistrationDate.replace(pattern, '$3-$2-$1'));

    if (reasonDt > registrationDt) {
        $('#ReasonDate').w2tag('@TranslateText("accard_ReasonDateShouldLessThanRegDate")');
        //$('#ReasonDate').addClass('w2ui-error');
    }
},

and on button click I'm validating like this:

add: function () {
    $('#BudgOrgTin').removeClass('w2ui-error');
    var errors = w2ui.form.validate(true);
    if (errors.length > 0) {
        return;
    }

How to add correctly my error message so that when I validate form it returns my error too?


Solution

  • I found the solution for this in the sources of w2ui:

    onValidate: function(event) {
      var pattern = /(\d{2})\.(\d{2})\.(\d{4})/;
      var reasonDt = new Date(w2ui.form.record.ReasonDate.replace(pattern, '$3-$2-$1'));
      var registrationDt = new Date(w2ui.form.record.RegistrationDate.replace(pattern, '$3-$2-$1'));
    
      if (reasonDt > registrationDt) {
    
         event.errors.push({field: this.get('RegistrationDate'), 
                            error: '@TranslateText("accard_ReasonDateShouldLessThanRegDate")'})
    
         // **no need for this anymore** w2ui does it for you
         // $('#ReasonDate').w2tag('@TranslateText("accard_ReasonDateShouldLessThanRegDate")');
         //$('#ReasonDate').addClass('w2ui-error');
      }
    },