Default input validation for every field

Default input validation for every field

matschematsche Posts: 14Questions: 6Answers: 0

I have several different datatables (with lots of columns) and every datatable has a own api (datatable editor php api).
I have to make sure that the user does not enter special characters (like cyrillic, mandarin, ..). Only ASCII characters should be allowed. It would be very cumbersome if I had to write the same validation for each field like:

Field::inst( 'user_name' )
->validator( function ( $val, $data, $field, $host ) {
    return preg_match( '/[\\x80-\\xff]+/' , $val )) ? true : 'Only ascii characters are allowed!';

Is there any option to make this validation as default for every column/field?



  • matschematsche Posts: 14Questions: 6Answers: 0

    When I am using the global validator the user only gets a global error message at the bottom. Example code:

    Editor::inst( $db, $db_table )
    ->validator( function ( $editor, $action, $data ) {
        if ( $action === Editor::ACTION_CREATE || $action === Editor::ACTION_EDIT ) {
            foreach ( $data['data'] as $row ) {
                foreach ( $row as $value ) {
                    if(!is_ascii($value)) {
                        return 'Only ascii characters are allowed! Check your input: "'.$value.'"';
    } );

    Is there an another way? The error message should appear next to the responsible text box.

  • allanallan Posts: 51,260Questions: 1Answers: 7,721 Site admin

    From a global validator the error message will always show in the general form error message. If you want it on a specific field you need to have the validator applied to the field instance.

    If you want to use the same validation function for multiple fields you could just create the function as a normal named function and reuse it:

    function myValidator ( $val, $data, $field, $host ) {
    // then
    Field::inst( 'user_name' )
    ->validator( myValidator )


Sign In or Register to comment.