Server side validation with dependent editor fields

Server side validation with dependent editor fields

lincolncbennettlincolncbennett Posts: 23Questions: 10Answers: 1

Hi Allan, further to this question https://datatables.net/forums/discussion/63624/apply-validation-to-many-fields I am also using dependent fields in my form for example in the code below I have the fields 'importtest.CurrentMarriageSpouseFamilyName' and 'importtest.PreviousMarriageSpouseFamilyName'.

->on( 'preEdit', function ( $editor, $id, $values ) {

        if ( $values['importtest']['task_status'] > '3') {
 
    $fieldNames = ['importtest.FamilyName', 'importtest.FamilyNameAtBirth', 'importtest.CurrentMarriageSpouseFamilyName', 'importtest.PreviousMarriageSpouseFamilyName' ];
 
     for ( $i=0; $i<count($fieldNames); $i++) {
     $editor->field($fieldNames[$i])

      //not empty
              ->validator( Validate::notEmpty( ValidateOptions::inst()
                ->message( 'A Family name is required' )
               ) )
             //not more that 70 characters
            ->validator( function ( $val, $data, $field, $host ) {
               return strlen( $val ) > 70 ?
            'Family name length must be 70 characters or less' :
            true; 
             } )
            //no numbers, lowercase 
            ->validator( function ( $val, $data, $field, $host ) {
               return preg_match('/^(([A-Z\'][A-Z \' -]*[A-Z\'])|([A-Z\']+))$/', $val) < 1 ?
            'Family name must not contain numbers, must be in capital letters, and can only accept apostrophies, dashes, and spaces' :
            true; 
             } );
}

Of course the 'importtest.PreviousMarriageSpouseFamilyName' field is only required if a previous marriage occurred so I am using editors dependent field option in the form to hide it unless a drop down field value equals the required value to show it.

 editor.dependent( [ 'importtest.NumberOfAdditionalMarriages'], function ( val ) {
      
       if  (editor.field('importtest.NumberOfAdditionalMarriages').val() == '1')

        {
          editor.field ('importtest.PreviousMarriageSpouseFamilyName').show();
         
        }
             return {};
   } );

When the 'importtest.PreviousMarriageSpouseFamilyName' field is hidden in editor it will still trigger the validation error which I understand is normal. I could include an aditonal if statement on the PreEdit function to detect if the dependent field is required or not, but I'm just wondering if there is a better way to do this?

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 61,611Questions: 1Answers: 10,089 Site admin
    Answer ✓

    What you describe is the way I would suggest doing it - check to see if the validator is needed or not based on the other data in the row submitted, and then validate it if needed.

    Allan

This discussion has been closed.