I'm using FAPI Validate to validate a mobile phone number using a regex. As this is one of the native FAPI Validate rule types, Clientside Validation has a handler for this, but it relies on an AJAX callback rather than the validation being performed natively in Javascript. I have Clientside Validation set up to run on Key Up, so after each key press in the field, the validation runs. The difficulty seems to be that the browser effectively locks up until the AJAX callback is returned, because of the 'async': false parameter set in the AJAX callback. The net effect is that at a normal typing speed, the browser only picks up 1 in every 3-4 characters.

I've opted to use a native JS implementation of the regex instead, which has solved the problem. Is there any reason why the regex validation could not be implemented natively in JS like the other rule types?

The current implementation:

jQuery.validator.addMethod("regexMatchPCRE", function(value, element, param) {
    var result = false;
    jQuery.ajax({
      'url': Drupal.settings.basePath + 'clientside_validation/ajax',
      'type': "POST",
      'data': {
        'value': value,
        'param': JSON.stringify(param)
      },
      'dataType': 'json',
      'async': false,
      'success': function(res){
        result = res;
      }
    });
    if (result['result'] === false) {
      if (result['message'].length) {
        jQuery.extend(jQuery.validator.messages, {
          "regexMatchPCRE": result['message']
        });
      }
    }
    return result['result'];
  }, jQuery.format('The value does not match the expected format.'));

Comments

attiks’s picture

It is like that in D7 version, but it never got backported, can you provide a patch

kaidawai’s picture

Hi,

problem was that php and js regex are way diffrent. So it is not posible to just feed js a php regex from FAPI.
Solution to this (for D7 ) was to use an additional js lib that translates rexp(that is very close to what php uses ) into js regexes.
Now that lib is also used by other modules which leads to conflicts in some cases(some versions of the lib complain when being included twice). So an additional module was created and Libraries2 was used to avoid such conflicts.
Now with Drupal 6 that solution is imho not 1:1 adaptable(in a way that doesn't break other stuff) - is it?. If it wasn't for this i'd provide a patch.

Just my 2ct.
Keep up the good work!

attiks’s picture

I think if we backport http://drupal.org/project/xregexp_api as well it should work.

kaidawai’s picture

Hi,
ok, i'd give it a shot. How do you want to go the xregexp module? Do you want a patch against the latest 7.x or do you create an initial 6.x branch(maybe from the 7.x) to diff against?

attiks’s picture

#4 @kaidawai is added you as a maintainer of xregexp_api so you can commit the 6.x version directly.

Thanks for your help.

kaidawai’s picture

StatusFileSize
new7.38 KB

Hi,
a first try. It's only rudymentary tested so don't expect it to work properly. Also i now remember that there where some quirks with the other module - iirc this was due to librarys2 was alpha last year and not really working and we tried to work around it. I guess 7.x needs some rework first and after that a 6.x backport makes more sence?
So don't expect too much it's more a pre alpha but better than nothing. See other comment at http://drupal.org/project/xregexp_api.

kaidawai’s picture

StatusFileSize
new7.38 KB

at least the extention should be patch ...

kaidawai’s picture

StatusFileSize
new7.73 KB

Hi,
now i did some additional minor testing. Fixed some obvious problems. It seems as if it at least works for some test-PCRE - even though it's still ugly( the xregexp module ).

kaidawai’s picture

@chiddicks
Are you following? Case you do: please check if it works for you. The clienside part is 90% code from 7.x so should be fairly ok. The xregexp code is admitedly not really an example of good coding. But for my testcases it works. And considering that we head towards 8.x please understand that i want to put no more effort in it than necessary to make it work for those who need 6.x.

But it needs some testing! This has to be done by someone else! So chiddicks if you are following and you realy need this functionallity, it would be awsome if you can try it! You'll find the xregexp-api module you need for it in git.

- Only issue i see now is that on the fly evaluation("keypress"/"keyup") needs some initiating trigger to start the validation. With 7.x an "on blur" event can serve as a trigger but not with 6.x. So it needs some other trigger e.g. a failing "submit" to initiate the validation. I have some feeling that this is a seperate issue but i look into this...

Jelle_S’s picture

I couldn't test the patch since in the xregexp_api 6.x version the library is never loaded because on line 75 you have:

<?php
if(empty($library) || !isset($library['variants']) || empty($library['variants'])){
?>

but $library['variants'] is an empty array.
It should either be filled with variants or skipped entirely

kaidawai’s picture

hi,
yes i know. See comment at xregexp module. Try to pull the newest 6.x-1.x from git. Should be fixed in git.
I am still straightening things up)... . Btw the Ajax fails too due to a wrong URL. There is an additional internal plugin makes some of the FAPI builtin REGEXes work(i clean that up as well and added it to git today).
Thanks for the reply.

kaidawai’s picture

Hi again,
no variants is only empty if only one lib is found otherwise the variants contains all other variants(if one extracts the Archive in the dir, there will be more than one..). The test was wrong...
Thanks.

kaidawai’s picture

see:
- http://drupal.org/node/1954230#comment-7259678
- Did further testing with variations of the form below(together with above).
- Did further testing with a slitely modified validate module that calls validate() on the text fields when loaded: with that on the fly validation does work and errormessages are shown and hidden while typing!

Note: /u flag is imo supported.
Note: '++' and \PL,\PN... are as well: i.e. the email field below also works without ajax call(doesn't in 7.x ).

<?php
 

function test_myform(&$form_state) {
  static
$unit = '(em|ex|px|in|cm|mm|pt|pc)?';
 static
$unitdesc = 'px,ex,em,in,cm,mm,pt,pc';        
  static
$unitp = '(em|ex|px|in|cm|mm|pt|pc|%)?';
 static
$unitpdesc = 'px,ex,em,in,cm,mm,pt,pc,%';
  static
$length = '\-?\d*\.?\d+(em|ex|px|in|cm|mm|pt|pc)?';
  static
$lengthp = '\-?\d*\.?\d+(em|ex|px|in|cm|mm|pt|pc|%)?';
  static
$intv = 'd+';
 
$form['myfield'] = array(
 
'#type' => 'textfield',
 
'#title' => 'EMAIL Weardness',
 
'#required' => TRUE,
 
'#rules' => array(
   
'email',
   
'length[10, 50]',
    array(
'rule' => 'alpha_numeric', 'error' => 'Please, use only alpha numeric characters at %field.'),
  ),
 
'#filters' => array('trim', 'uppercase')
  );
 
$form['numeric'] = array(
 
'#type' => 'textfield',
 
'#title' => 'Numeric',
 
'#required' => TRUE,
  
'#rules' => array(
   
'numeric',
  ),
  );
 
$form['numericdash'] = array(
 
'#type' => 'textfield',
 
'#title' => 'Numeric-dash',
 
'#required' => TRUE,
  
'#rules' => array(
   
'numeric-dash',
  ),
  );
 
  
$form['ipv4'] = array(
 
'#type' => 'textfield',
 
'#title' => 'IPV4',
 
'#required' => TRUE,
  
'#rules' => array(
   
'ipv4',
  ),
  );

 
$form['name'] = array(
   
'#type' => 'textfield',
   
'#title' => t('Name'),
   
'#size' => 30,
   
'#maxlength' => 64,
   
'#description' => t('Enter the name for this group of settings'),
   
'#rules' => array(
        array(
         
'rule' => 'regexp[/^(' . $length . '|normal|inherit)?$/]',
         
'error' => t('numeric value + unit(@u) or normal, inherit', array('@u' => $unitdesc)),
        )
      )
  );
 
$form['name2'] = array(
   
'#type' => 'textfield',
   
'#title' => t('Name2'),
   
'#size' => 30,
   
'#maxlength' => 64,
   
'#description' => t('Enter the name for this group of settings'),
   
'#rules' => array(
        array(
         
'rule' => 'regexp[/^(' . $length . '|normal|inherit)?$/]',
         
'error' => t('numeric value + unit(@u) or normal, inherit', array('@u' => $unitdesc)),
        )
      )
  );
 
$form['url'] = array(
   
'#type' => 'textfield',
   
'#title' => t('URL'),
   
'#size' => 30,
   
'#maxlength' => 64,
   
'#description' => t('an URL'),
   
'#rules' => array(
        array(
         
'rule' => 'url',
         
'error' => t('valid url required'),
        )
      )
  ); 
 
$form['submit'] = array('#type' => 'submit', '#value' => t('Save'));
  return
$form;
}
 print
drupal_get_form('test_myform');
?>

Hope the code in git works as well ... ;)

Jelle_S’s picture

Version:6.x-1.32» 6.x-1.x-dev
Status:Active» Needs work

Patch works with the latest git clone of xregexp_api 6.x and with xregexp 2.0
The only problem now is that when I don't include your xregexp-php.js file I get the following error after refreshing the page:
warning: Invalid argument supplied for foreach() in /home/quickstart/websites/validation6.dev/sites/all/modules/clientside_validation/clientside_validation.module on line 122.
This is after I fill in an email address in the first field of your form and has something to do with the alphanumeric rule. Apparently jQuery.ajax does not properly serialize its data somehow. I assume this is a jQuery bug, but none the less it seems like this is something that would have to be addressed.

The rest of it all seems to work brilliantly ;-)

Jelle_S’s picture

StatusFileSize
new56.1 KB
new53.23 KB
new14.46 KB

Note: '++' and \PL,\PN... are as well: i.e. the email field below also works without ajax call(doesn't in 7.x ).

The email field does work ik 7.x with xregexp strangely...
As you see, no extra xregexp files loaded besides those included in the standard (2.0) library and the alphanumeric regex works as you'd expect. But this seems like something to be solved in a separate issue (for xregexp_api).

Selection_048.pngMenu_046.pngTooltip_047.png

kaidawai’s picture

StatusFileSize
new7.7 KB

well i removed the line in the patch 8 - )

and regarding the mail field: i see its actually \P{L} in 7.x and not \PL - cool cool.

Jelle_S’s picture

Status:Needs work» Fixed

Committed and pushed to the latest dev. I removed some trailing spaces and changed the regexs to match those in 6.x, so your custom plugin is not necessary. You might want to consider pushing it upstream as it might be usefull to other people (just a thought).

Thanks a million for all your work on this! ;-)

Status:Fixed» Closed (fixed)

Automatically closed -- issue fixed for 2 weeks with no activity.

chiddicks’s picture

Wow, thanks for all the work on this. I will be trying it out as soon as I get an opportunity.