Apply validation to many fields

Apply validation to many fields

lincolncbennettlincolncbennett Posts: 23Questions: 10Answers: 1

Hi, I am just wondering is it possible to apply multiple validations to multiple fields at a time? I am using editor with a large form (50 fields) and applying validations server side. I'm wanting to apply the same validation to many fields. I am trying this.

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

        if ( $values['importtest']['task_status'] > '3') {
 
            $editor
            ->field( 'importtest.FamilyName', 'importtest.FamilyNameAtBirth' )
            
             //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; 
             } );
    }
 
})

this is causing error on update. It works fine if I remove 'importtest.FamilyNameAtBirth'.

Any help would be appreciated.

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 61,722Questions: 1Answers: 10,108 Site admin
    Answer ✓

    No - I'm afraid that field() can only take a single argument (which is probably the error you are getting?).

    You'd need an array of the fields you want, and then loop over them adding the validators to each - e.g.:

    $fieldNames = ['importtest.FamilyName', 'importtest.FamilyNameAtBirth'];
    
    for ( $i=0; $i<count($fieldNames); $i++) {
      $editor->field($fieldNames[$i])->validator( ... );
    }
    

    Allan

  • lincolncbennettlincolncbennett Posts: 23Questions: 10Answers: 1

    Ah, many thanks Allan, worked perfect. Really appreciate your help. :)

This discussion has been closed.