开发者

How do I use the livevalidation javascript library custom.validation function?

开发者 https://www.devze.com 2022-12-08 21:15 出处:网络
(note: my original question was not linked to my openid - I am reposting here to be able to edit/update/respond accordingly - if anyone with access could remove the original question: /questions/15549

(note: my original question was not linked to my openid - I am reposting here to be able to edit/update/respond accordingly - if anyone with access could remove the original question: /questions/1554916/how-to-use-the-livevalidation-javascript-library-custom-validate-function that woudl be great !!)

Heya Folks,

I am very new to all of this so please bear with me!

I have mangaged to create a form with livevalidation checking of fields, and also with an ajax/json check to see if a usename is valid. I seem to get along fine with standard live validation.

Here is a demo of what I have at the moment: link text

The method to give a responce to the ajax username check simply changes a with a message in to make it visable, so I want to use a livevalidation check to manage the ajax responce - so I can link them together (check for blank, then in use, then invalid, then pass as ok) and have my responses output the same way.

I currently have this form code:

<?php

$script = "
$('uname').addEvent('blur', function(e) {
   e = new Event(e).stop();
   // Show the spinning indicator when pressing the submit button...
   $('indicator1').setStyle('display', 'block');

   var username = $('uname').value;
   if ( username != '' ) {
        var url = 'index.php?option=com_chronocontact&chronoformname=custom_livevalidation_test&task=extra&format=raw';
        var jSonRequest = new Json.Remote(url, {
           onComplete: function(r) {
              $('indicator1').setStyle('display','none');
               if ( r.username_ok ) {
                 $('username_msg').setHTML(\"<span style='color:green;'>Username '\"+username+\"' is OK</span>\");
              } else {
                 $('username_msg')开发者_开发技巧.setHTML(\"<span style='color:red;'>Sorry, username '\"+username+\"' is already taken</span>\");
              }
         }
      }).send({'username': username});
   }
});
";

global $mainframe;
if ($mainframe->isSite())
{

$doc =& JFactory::getDocument();
$script = "
window.addEvent('domready', function() {
$script
});
";
$doc->addScriptDeclaration($script);
};


$script = "
var uname = new LiveValidation('uname', { 
  validMessage: 'This is a valid username', 
  wait: 500
});
uname.add(Validate.Presence, {
  failureMessage: 'Username must not be blank!'
});
uname.add(Validate.Format, {
  pattern: /^[a-zA-Z\-_]{4,16}$/, 
  failureMessage: 'Username must be between 4 and 16 characters' 
});
";

global $mainframe;
if ($mainframe->isSite())
{

$doc =& JFactory::getDocument();
$script = "
window.addEvent('domready', function() {
$script
});
";
$doc->addScriptDeclaration($script);
};
?>


<div>
<span class="cf_label">Username: </span>
<input style="" id="uname" name="uname" class="" title="" value="" type="text">
<span id="indicator1" style="display: none"><img src="/images/hourglass.gif" alt="checking..." /></span>
<div id='username_msg'></div>
</div>
<br />
<input type='submit' name='submit' value='submit' />

With this being the json part that runs in the background:

<?php
$json = stripslashes($_POST['json']);
$json = json_decode($json);

if ( $json->username ){
    $db =& JFactory::getDBO();
    $query = "
        SELECT COUNT(*)
           FROM `jos_users`
           WHERE `username` = ".$db->quote($json->username).";";
    $db->setQuery($query);
    $response = (bool) !$database->loadResult();
    $response = array('username_ok' => $response );
    echo json_encode($response);
}
?>

So looking at the livevalidation documentation, you can use a custom validation in this fashion:

// Pass a function that checks if a number is divisible by one that you pass it in args object
// In this case, 5 is passed, so should return true and validation will pass
Validate.Custom( 55, { against: function(value,args){ return !(value % args.divisibleBy) }, args: {divisibleBy: 5} } );

I am finding this to be very cryptic - I would think I should be able to point to 'function(r)' thats all ready there - but I doubt I am doing it the right way,

Can anyone shed any light, I am (hoping!) to understand it as well as uncover a solution!!

* Updates *

I am now led to believe that this code for the validate.custom part should work:

var uname = new LiveValidation('uname', { 
  validMessage: 'This is a valid username', 
  wait: 500
});
uname.add(Validate.Presence, {
  failureMessage: 'Username must not be blank!'
});
uname.add(Validate.Custom('uname', { against: function(r){
return !(r.username_ok) }, args: {} } ),
failureMessage: 'This username is already taken' 
});
uname.add(Validate.Format, {
  pattern: /^[a-zA-Z\-_]{4,16}$/, 
  failureMessage: 'Username must be between 4 and 16 characters' 
});
";

However it seems that I have an architecture issue - live validation wants an instant answer, and ajax takes place in the background. I have had a suggestion to investigate the 'observer pattern' thats an entirely new concept to me - I am usually playing with the graphical design and structure side of a cms!

Any further help / clarification appreciated as I will have to come back to this and get it working!!


try the code sample in the following link. It worked for me. The key is to write the logic in a separate JavaScript function and call it with the Validate.Custom function.

http://www.experts-exchange.com/codeSnippetPopup.jsp?csid=259114

Edit: Added code from the link:

//input Form
<form  action="#" method="post">
    <label for="ip">IP:</label>
    <input type="text" name="ip" id="ip"/>
    <br/>
    <label for="ip">Case:</label>
    <input type="text" name="ticket" id="ticket"/> 
    <br/>
    <input type="submit" value="Submit" name="submit" onclick="checkInput()"/>                          
</form>

/// JS function
function checkInput() {
    var ip = new LiveValidation('ip', {onlyOnSubmit: true } );
    ip.add( Validate.Presence );
    ip.add( Validate.Custom, { against: function(value){ return isValidIPAddress(value) }, failureMessage: "IP is not valid" } ); 
    var ticket = new LiveValidation('ticket', {onlyOnSubmit: true } );
    ticket.add( Validate.Presence );
    ticket.add( Validate.Custom, { against: function(value){ return Case(value) }, failureMessage: "Case is not valid" } ); 

    var ipSubmit = ip.form.onsubmit;
    var ticketSubmit = ticket.form.onsubmit;
    ip.form.onsubmit = function(){
    var validIP = ipSubmit();
    var validCase = ticketSubmit();
    if((validIP)& (validCase))
       getActionBack('0');
       return false;
    }
}


Here's another example that works.

f1.add(
   Validate.Custom, 
   { 
      against: function (value, args) { return isValidCreditCard(value, args.cardType) }, 
      args: { cardType: "Visa" }, 
      failureMessage: "Credit Card number is not valid" 
   }
);

The weird part is...

against: function (value, args) { return isValidCreditCard(value, args.cardType) }

...which has my isValidCreditCard function nested inside the 'against' function. The against function just returns what my isValidCreditCard function returned.

You can put the actual function there instead just like the cryptic example, but anything more than a line would probably be quite confusing. (Why use % [modulus] in the example? No one knows that operator!)

0

精彩评论

暂无评论...
验证码 换一张
取 消