Viewing 5 reply threads
  • Author
    Posts
    • #10635
      courtens
      Participant

      I am trying to validate a field; accepting only 0-9 and must have 3 values; for instance 000 would work, and any combinations of that up to 999.

      (code is part of a group)

      ,array(
      	'type' => 'tel'
      	,'field' => 'number'
      	,'label' => 'Number'
      	,'attributes' => array(
      		'style' => '-moz-appearance: textfield;'
      	)
      	,'required' => true
      	,'pattern' => '\d{3}'
      )
    • #10638
      Steve
      Keymaster

      You can easily create your own validation rules to use with Piklist:
      https://docs.piklist.com/actions-filters/filters/piklist_validation_rules/

    • #10640
      courtens
      Participant

      I got my function, but how would I implement this? (sorry, I am new to php and piklist)

      function CheckIfStrOnlyNumbers($teststring,$needsMatch) {
          if (ctype_digit($teststring) and $needsMatch = strlen($needsMatch)) {
              return true;
          } else { 
              return false;
          }
      };
      
      echo CheckIfStrOnlyNumbers('103',3);
    • #10643
      Steve
      Keymaster

      First you need to write your custom validation function. Using your code snippet, above, and using the Piklist “range” validation rule as a template because it’s similar, I came up with this:

      function validate_number_length($index, $value, $options = null, $field, $fields) {
          extract($options);
      
      	$passed_value = $field['request_value'][0];
      	$required_length = $options['length'];
      
         if (ctype_digit($passed_value) and $needsMatch = strlen($required_length)) {
              return true;
          } else { 
      		return sprintf(__('contains a value that is not %s characters', 'piklist'), $required_length);
          }
      }

      Next add a function that filters piklist_validation_rules and calls your function:

      add_filter('piklist_validation_rules', 'check_number_length', 11);
      
        function check_number_length($validation_rules) {
          $validation_rules['number_length'] = array(
            'callback' => 'validate_number_length'
          );
      
          return $validation_rules;
        }

      Then you would use it like this:

      piklist('field', array(
          'type' => 'number',
          'field' => 'my_field',
          'label' => 'my field',
          'validate' => array(
      	array(
      		'type' => 'number_length',
      		'options' => array(
      			'length' => 3
      		),
      	)
          )
      ));

      This is untested.

    • #10646
      courtens
      Participant

      Thank you. That worked (after removing the extra comma.)

    • #10647
      Steve
      Keymaster

      Happy to help!

Viewing 5 reply threads
  • The topic ‘how to validate numbers inside type text or type tel’ is closed to new replies.