Coder Social home page Coder Social logo

validetta's People

Contributors

adammacias avatar akkiros avatar dimensi avatar edwinhoksberg avatar emr avatar hsnaydd avatar jherencia avatar mrezasafari avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

validetta's Issues

handler pending line 425

I wonder if there is still any life here? 2014 was the peak... :)

Anyhow, I am pressing on.
Simple login > 2 fields to check against a small database. Both fields have
data-validetta='remote[check_change]'
Basically it works BUT... once both fields are true - to get the onValid to fire - I need to force another error - then it fires.
event.preventDefault(); alert( event.isDefaultPrevented() ); // true
This has been a bit of a hair puller. What I am currently testing is remming line 425
this.handler = 'pending';
I am only an amateur but wonder why, at the end of all the remote testing, this is thrown in.
I get positives for line 368 & 412 -- ie. all is good and clear but then... we are back to pending.

I will test this with other forms but so far taking out that closing line seems to fix it.

Anyone????

Adding attibute data-vd-parent-up

Sometimes you may want to change parent of inputs for display error messages in upper element.This feature allows you to add error messages into the upper element.

onsubmit testing - final closure

Hi Hasan, I am close but have still to resolve my aims. I hope you have time to help.

1 - I see your point with the this.handler = 'pending'; and am working with that line active.
2 - I am aiming to recode all my forms and am working with one of the more simple - a sign-up.
3 - I want to validate and submit data to file while maintaining page state
4 - I see the asynchronous (one by one) nature of validetta so have been using a CSV temp file to record each field as it is validated. Works fine - providing that the submit button is not clicked while there are errors.
5 - Here is an example
http://bodhinyanarama.net.nz/news/subScribeTest.php
I have used $_SESSION to track state toggling from XYZ to > F [first] L [last] M [mail]
6 - If you enter data for 'first' then shift focus you can see this updated in:
http://bodhinyanarama.net.nz/news/testTMP.txt
Then enter data for second > test in TMP.txt
Then click submit. You will see the error as FLZ [no email so Z has not been changed to M]
7 - If I go back and change first or last these changes are visible in TMP.txt But if I enter a valid email that change is registered in TMP.txt -- ie. the remote call is working. BUT
8 - No way can I get the onVaild to fire.
9 - If you reload the form and enter all data correctly and then click submit -- YES > Bingo! > onValid message is printed.
check database result"
http://bodhinyanarama.net.nz/news/test_news.db

What is blocking the clearance of the submit error - valid => false ?
Or is there something else I am missing?

code:
http://bodhinyanarama.net.nz/news/subScribeTest.txt [the form]
http://bodhinyanarama.net.nz/news/subScribeINTest.txt [remote php]

Trigger remote validators onChange

Tried to find the similar questions but couldnt find :(

There is a input checkbox and I would like to trigger one of remote validators whenever the checked change. I can only see the validator works only first click but not after second.

Would be really appreciate if someone can let me know how to.
Thanks in advance.

validetta with autocomplete

when I select an item in the jQuery autoComplete list and it lost the focus, the bubble not disappear.
You can see all the fields above it we have Validetta, and everyone is ok (invisible bubble/validated), the problem is just with jQuery AutoComplete labeled Comprador.

image

jumpTo error on submit

Another code suggestion.
When the user clicks 'submit' the page scrolls to any error - in the case of more than one error it jumps to the topmost error.

line 469: add class 'jumpToError'

errorObject.className = this.options.errorTemplateClass + ' jumpToError '+this.options.errorTemplateClass + '--' + this.options.bubblePosition;

in the docReady jquery

$('#guestForm').submit(function() {
$('html, body').animate({
scrollTop: $(".jumpToError").offset().top-22+'px'
}, 1000); 

I have tested this in FF - IE - Chrome & Safari and it is consistent.

Feature: Add Custom Error Messages

Add ability to read custom error messages per field by type with data-error-[type] attribute.
Example:
<input type="text" name="phone" value="" data-validetta="required,number" data-error-required="This field is required." data-error-number="Please enter a valid phone number.">

<input type="text" name="email" value="" data-validetta="required,email" data-error-required="This field is required." data-error-email="Please enter an email address in the correct format.">

Also add ability to customize global error messages by extending options.

Form being sent when showing modal element

When showing a modal element (I am using bootstrap) the submit event is being triggered. The function inside "onValid" is executed, even with "realTime : false".

Is this the correct behavior?

If a form's fields are completely correct and the modal is shown, the form is submitted. Although that is not my intention.

v2 Task List

  • Removing jQuery dependency [e66b624]
  • [bug] breaking validation if selectbox's first option is disabled [cb78341]
  • Adding top and left choices to bubblePosition option [16633b2]
  • Disabling error messages show option from data attribute [3aefeb1]
  • [bug] Error messages which coming from remote validation via getInvalidFields are not accessible [a28db15]
  • Refactoring reseting errors functions [b8b2d5e]
  • [bug] Disabled checkboxes validating [2b14f13]
  • [bug] Validate on keyup rather than only input blur #43
  • [bug] Manually display error message doesnt work #44
  • Changing regExp validator name as pattern
  • Defining validators with native Input types and required attribute (deferred to the v3)
  • Moving gulp and using eslint
  • Refactoring code (deferred to the v3)
  • Writing tests (deferred to the v3)
  • Adding docs for how to validate phone, ip etc
  • Updating docs section on jQuery
  • Updating docs section on bubble options
  • Updating docs section on regExp validator
  • Example of date validation #49
  • Destroy instance #46 (deferred to the v3)
  • Re initialization after adding dynamic inputs #34` (deferred to the v3)

Email validation

The regular expression to validate email addresses seems to the see an address like asdf@dasdf as a valid address.

if you change the RegExp on line 19 to:

/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/

an address like the one above doesn't pass the validation.

Custom callback validator not firing when input is blank

I have a custom callback validator that does not fire when I initially submit the form if the input value is blank. My custom validator callback is checking to see if two different inputs are blank (the one the validator is one, and the other I grab in the callback), as at least one is required.

Here's my custom validator callback:

...
callback: {
    email: {
        callback: function(el, value) {
            var phone = $('#primaryContactForm input[name="phone"]');
            return !(value === '' && phone.val().trim() === '');
        },
        errorMessage: "You must provide your email address or phone number."
    }
}
...

Running version 1.0.1
Google Chrome 59.0.3071.104 on macOS 10.12.4

Specify error template

I have a use case where I need to add an icon in front of the error message. I'd like to do this globally by defining a template in the initialization settings.

For example, the settings could look like:
templates: { errorTemplate: '<span class="%errorTemplateClass%"><span class="my-icon"></span>%errorMessage%</span>' }

Çalıştıramadım

Öncelikle çok kullanışlı bir toola benziyor. Ellerine sağlık.
İlk "issue" bana nasip oldu haydi hayırlısı :)
Bir form üzerinde en basit örneklerinden birini uygulamaya çalıştım.
Forma bir input koydum. ve altına gerekli scripti ekledim. Ancak bende çalışmadı.
jQuery v1.11.1 ile Chrome üzerinde deniyorum.

login <script type="text/javascript"> $(document).ready(function(){ $('#test').validetta({ // this -> form object // this.form is form element onValid : function( event ){ event.preventDefault(); // if you dont break submit and if form doesnt have error, page will post var _inp = $('#test').find('input[name="name"]'); this.window.open.call( this, _inp, 'This is an example about how you can focus an input after completion of form validation.'); }, realTime: true }); } </script>

Fade Alert on focus

Hi. Just stumbled over your very cool and easy validation plugin.

One question tough: Is it possible, that when an error appears, the alert message automatically disappears when you focus the input field to correct the error?

Thank you.

Destroy instance

Hi Hasan,

Really like you plugin. Sometime, i need to destroy validetta. But couldn't find it on docs. Is there any way to destroy/ delete/ clear the instance?

Thanks!

Capital letters in email address breaks validation

Love the plugin. However we're having an issue where if the first letter is capitalized in an email (which is sometimes automatic, especially on mobile) the email error pops up. How do we allow a capital letter for email validation?

Thanks

Error in documentation?

Checking methods : required,customReg[regname]

(function($){
    $('#exm8').validetta({
        customReg : {
            exmreg : {
                method :  '/^hello$/',
                errorMessage : 'Please type hello !'
            }
        },
        realTime : true
    });  
});

It doesn't work for me, if regex in quotes (method: /^hello$/ works fine for me)

equalTo validator fails to work when name has square brackets

CakePHP uses square brackets in input elements, for example:
<input type="text" name="model[field]">

When adding equalTo it fails to validate, for example:
<input type="text" name="model[field]">
<input type="text" name="modal[field_confirm]" data-validetta="equalTo[model[field]]">

I had to write a callback to make the check.

Re initialization after adding dynamic inputs

Hi guys.

Is there a way to refresh the plugin once it is initialized?
I'm trying to add some dynamic inputs on my form, but realTime validation is not working on new inputs,
and if I call again $('form').validetta({..}) it creates multiple instances of validetta class (new Validetta( this, options )), so I'm getting multiple onValid and onError methods for each instance.

Hope you can help.
Thanks.

Check for radio Button group

Hi.

How do I check for a radiobutton group?

<div class="radio">
   <label for="sia_1">
         <input type="radio" name="sia" id="sia_1" value="" checked>Nichts
    </label>
</div>
<div class="radio">
   <label for="sia_2">
         <input type="radio" name="sia" id="sia_2" value="SIA 1 Periode">«SIA Merkblatt 2028»: 1 Periode 
   </label>
</div>
<div class="radio">
   <label for="sia_3">
         <input type="radio" name="sia" id="sia_3" value="SIA 3 Periode">«SIA Merkblatt 2028»: 3 Periode 
   </label>
</div>

If I just add data-validetta="required" or data-validetta="minChecked[1]" it breakes the whole vailadion on every formfield.

Sending a file

Hi Hsnayd!

I'm trying to send a file via email within a form and use the callbacks to deal with it, but without success.

Something like this...

onValid : function( event ) {
event.preventDefault();
$.ajax({
type : 'POST',
url : 'send.php',
data : $('form').serialize(),
success: function() {
alert("Success!");
}
});
},

Can't you give-me some hints on these?

Thanx a lot. Best regards, Pedro Coelho.

remote compare field values using $_session

Hey Hasan. I got distracted but am back enjoying validetta. Real glad you are still working on it.
How's the knee?

getting up to speed again and my first block...

a simple sign in form - 2 fields - name/email
I need to test both fields against the database and check that they are a matched pair.
emails are unique but there could be more than one "Bob" registered. I could just rely on testing the email address but I would like the extra security (admittedly low level) of testing against the name.
Here is my code - where 'first' is the firstName

    $datafile = 'test_news.db';
    $record = file($datafile);
    $rec = count($record);
    if(isset($_POST['first'])) { $fname = strtolower($_POST['first']);
    for ($i=1; $i<$rec; $i++) { $row = explode("|",$record[$i]);
    if (strtolower($row[0])==$fname) { 
    $_SESSION['fName'] = $fname;
    $response = array( 'valid' => true ); break; } // match
    elseif (strtolower($row[0])!=$fname) { // no name match
    $_SESSION['fName'] = 'badName';
    $response = array( 'valid' => false, 'message' => 'Name not found' ); }
    } // END for loop
    }
    if(isset($_POST['email'])) { $mail = strtolower($_POST['email']);
    if(isset($_SESSION['fName']) && $_SESSION['fName']!='badName') { $loginName = $_SESSION['fName']; }
    else { $loginName='eitherBadOrEmpty'; }
    for ($i=1; $i<$rec; $i++) { $row = explode("|",$record[$i]);
    if ( strtolower($row[2]) == $mail ) {  // match
    if (strtolower($row[0])!=$loginName) { unset($_SESSION['fName']);
    $response=array('valid'=>false, 'message' => 'Must pair with Name '.$loginName); break; }
    else { $_SESSION['loginEmail'] = $mail; // for use on editing
    $response = array( 'valid' => true ); break; } // ALL OK        
    }
    else { $response = array( 'valid' => false, 'message' => 'Email not found'); }
    } // END for loop

My theory is that the fName session should be updated each time that field is modified. It seems not.

I thought that the code alone might reveal my mistake to you. Yes?
I have set a text example of the above >
http://bodhinyanarama.net.nz/news/formTest.php

If you type fName as 'sdfdf' then error = 'Name not found' -- correct
Then type eMail as 'red@red' that error = 'Must pair with Name eitherBadOrEmpty'
Then correct the name to 'Red' - and my logic says this should reset the session value.
Then change the email to 'sdf@asd' - then back to 'red@red' - the error remains the same.

Why does the session not update?

Thanks

v1.0.1 - comments + left side

Hey Hasan, I have been testing but also quite distracted with other projects.

All is good! I am almost ready to implement. Awesome.

I saw in your closing comment to my last# that you had bubblePosition : left in v1.0.1
I just looked at the latest posting and couldn't see it so here is my working of that. It may save you some time.

defaults {
display : 'bubble', // I would add a comment here so users are clear that errorTemplateClass 
// requires changing to match 'display' -- or you could recode to set css using 'display' setting
// [as you have done for the bubble arrow >> +'--'+this.options.bubblePosition; ]
bubblePosition: 'left', // Bubble position // right / bottom / left / inline
}

before line 463 // if error display is bubble... need to declare innerHTML to get bubble width

elParent.appendChild( errorObject );
errorObject.innerHTML = '';
errorObject.innerHTML = error; // add error text here to get width of bubble

then [I have included the entire block here and figure that my changes are clear enough

if( this.options.display === 'bubble' ) {
var pos, bubbleMax, bubWide=0, W=0, H=0;
// !! Here, JQuery functions are using to support the IE8
pos = $( el ).position(); //  the properties top and left > position.left + position.top
    bubWide = $(errorObject).width(); // width of bubble; incl. message 

// only small space left or right of input
if (this.options.bubblePosition === 'left' && 
    (pos.left<this.options.bubbleMin || pos.left<bubWide+15)) { 
        errorObject.innerHTML = 'Error';
        bubWide = $(errorObject).width(); }
if (this.options.bubblePosition === 'right' && $(window).width()-(pos.left+el.offsetWidth)<this.options.bubbleMin) { 
    errorObject.innerHTML = 'Error'; }

if ( this.options.bubblePosition === 'bottom' ){ H = el.offsetHeight+2; }
else if ( this.options.bubblePosition === 'left' ) { W= -(this.options.bubbleGapLeft*2); 
errorObject.style.right = Math.floor(($(window).width()-pos.left)+2) +'px'; // so span will wrap
     }
else { W = el.offsetWidth; } // set right
//errorObject.innerHTML = ''; // set above
errorObject.style.top = pos.top + H + this.options.bubbleGapTop +'px';
if (this.options.bubblePosition !== 'left') { 
    errorObject.style.left = pos.left + W + this.options.bubbleGapLeft +'px' }
} // END bubble

My understanding of ajax is improving. Old brain = slow progress :)
thank you

Empty is valid

Empty input is parsed as valid on some types of input, namely credit card.

Using without a form?

I want to use this plugin but I need to use it without a form tag nor submit button, is there any way to call a method to make a programmatic validation?

Thanks in advance
Luis

API Validator

Providing access to Validator from callback function which onError and onValid

Long custom validator names don't work

It seems like the custom validator names are limited to 15 characters, but I can't find any mention of it in the documentation. I'm not really sure why that would be the case. Is there a reason for this or some sort of bug?

Here's my code:

JS:

$(document).ready(function() {
        $('#exm1').validetta({
            validators: {
                callback: {
                    visibleRequired: {
                        callback:  function( el, value ) {
                          return false
                        },
                        errorMessage: "This message shows."
                    },
                    visibleRequiredAndSomeMoreWords: {
                        callback:  function( el, value ) {
                          return false
                        },
                        errorMessage: "This message shows does not show."
                    }
                }
            },
            realTime : true
        });
    });

HTML:

<form id="exm1" method="POST" action="#">
    <div>
        <label>Callback :</label>
        <input type="text" name="callback" data-validetta="callback[visibleRequired]" />
    </div>
    <div>
        <label>Callback :</label>
        <input type="text" name="callback" data-validetta="callback[visibleRequiredAndSomeMoreWords]" />
    </div>
    <button type="submit">Submit</button>
</form>

Setting to only apply validation to visible fields

I have some form fields which are conditionally shown on the page. They only need to be validated against if they are not hidden. Currently validetta will run the validation on them and stop the form from submitting, even if they are hidden.

Is there a setting to only have validation apply to visible fields?

validetta and areYouSure

validetta is a wonderful Jquery addin. I need to use both validetta and the areYouSure Jquery addin on the same form,

My problem is that after a Post attempt on a "dirty" form, that adds validetta "flags", the form no longer has the class='dirty' . I thought I might be able to set the class=dirty and then use the validetta onCompleteFunc to trigger rescan.areYouSure. I don't seem to be able to set the class = dirty or trigger the rescan. am I missing something with onCompleteFunc?

<SCRIPT language=javascript> $(document).ready(function(){ $('form').areYouSure({ 'message':'Your school information has not beed saved!' }); $('form').validetta({ onCompleteFunc :function(){ $('form').addClass('dirty'); // check again to see if form data has changed after validation is complete $('form').trigger('rescan.areYouSure'); } }); }); </SCRIPT>

radio error positioning

In a radio button sequence , currently the error bubble is set immediately to the right of the first radio. This obscures all the other buttons and the only solution is either to set a close "X" on the bubble or click that first radio and then make the choice.

I have made a couple of attempts to alter this but haven't given too much time.
The error is thrown in the 'switch'
and...

var count = this.form.querySelectorAll('input[type=radio][name="'+ el.name +'"]').length;

counts how many there are in the series.
I fiddled about with both but thought to see if you have any suggestions Hasan?
I wouldn't say it was a bug - more a design flaw.

Date: predate test; suggestion

I am not sure if this is useful? I wondered about you having a space for add-ons, or snippets - which is really what this is. I imagine different users create bits of code - that work for them - and could be useful for others. You could list - but not support or guarantee.
Anyhow...
This uses date format yyyy-mm-dd or,
yyyy-mm-dd hh:mm

messages = {
... as per,
mustPostDate : 'Depart <i>after</i> Arrival'
},

  Validator = {

    // postDate check; end date must be after start date
    postDate : function( tmp, self ) { 
            var startDate = self.form.querySelector('input[name="'+ tmp.arg +'"]').value;
        if (startDate.length>'0') { // startDate must be set
            // work on start date
        if (/ /g.test(startDate)) { // with time: "yyy-mm-dd HH:MM" - 24hr clock
            var startRaw = startDate.split(' ')[0].split('-');
            var timeRaw = startDate.split(' ')[1].split(':');
                var hours = timeRaw[0];
                var mins = timeRaw[1]; }
        else { var startRaw = startDate.split('-'); // plain date: "yyy-mm-dd"
            var hours = '0'; var mins = '0'; }
        // Date.UTC(yy,mm,dd,hh,mm,ss); = milliseconds
    var startStamp = Date.UTC(startRaw[0],startRaw[1]-1,startRaw[2],hours,mins,0)/1000;
            // work on end date
        if (/ /g.test(tmp.val)) { // with time: "yyy-mm-dd HH:MM" - 24hr clock
            var endRaw = tmp.val.split(' ')[0].split('-');
            var timeRaw = tmp.val.split(' ')[1].split(':');
                var hours = timeRaw[0];
                var mins = timeRaw[1]; }
        else { var endRaw = tmp.val.split('-'); // plain date: "yyy-mm-dd"
            var hours = '0'; var mins = '0'; }
    var endStamp = Date.UTC(endRaw[0],endRaw[1]-1,endRaw[2],hours,mins,0)/1000;
            return endStamp >= startStamp || messages.mustPostDate; }
       else return; // startDate not yet set
    },
// etc...
  }; // END Validator =

I think that's it.

submit form via php

Hi!
Great "validetta" hsnayd!!
I'm just havin an issue on sending the form via php without comment the "event.preventDefault();" on the "onValid" option.
What I would like to do is to send the form without refreshing the entire page, because that will hide the final validation feedback.
Really need your expertise on this one.
I tried with this with no good returning:

onValid : function( event ) {
event.preventDefault();
$('#alert').empty()
.append('

Nice ' + name1.value + '!
');
$("#form").submit(function() {
$.post($(this).attr("action"), $(this).serialize(), function(data){});
return false;
});
}

Thanks for your time.
Beste regards,
Pedro Coelho.

ajax's data property

Hello their sir, I would like to ask if it's possible to use the data property of ajax in your custom ajax request and can I declare some variables inside the validetta, if yes how :)
Thanks in advance

saving form data

It would be good to see an example that shows how you would save the final, validated form.

Back in #27 I asked about feeding data back to validetta and you suggested that we could only handle a JSON formatted object. This stumped me for a while.

To work both saving and data feedback I have used

, onValid : function(event){ event.preventDefault(); $.post("subScribe.php",
$(this.form).serialize()).done(function(data) { var newRec = data.replace(/"/g,'');
newRec = newRec.split('|');
alert(newRec[0]);  // etc.

I can't seem to get $_POST to recognize the submit name/value so I have used a hidden field [name=fake], which requires a: data-validetta='??'. This is only submitted if all other (visible) fields are validated - so I then use

// in php
if (isset($_POST['fake']) { 
// get all field $_POST values
// save to file 
$response = $val1.'|.$val2; }
echo json_encode($response); // at the bottom of all remote files

The .done(function(data) holds a quoted string [$response] which can then be manipulated [as above]

I am sorry if this is in any way 'off topic' and I would be very interested in your thoughts on this.

arfa

validate for input name

i have tried for create my own validation add but doesn't work
Please help me

Only alphabet

message on left side

I am doing a responsive rewrite on an old site with client-side validation as a part. As an amateur coder I wanted something simple but with basic functionality. I have enjoyed working with your code -- nice and clean with plenty of comments -- and have added a couple of functions.
The first thing I did was add a resize command to the form page. I would recommend this as part of your dist. zip. With absolute positioning it looks awful to see those lovely bubbles sprawling every which a way on resize.

    window.onresize = validettaResize;
    function validettaResize() { $('.validetta-bubble').hide(); }

The function that might be generally useful is left-side positioning. I have a couple of instances with elements on the right of the form so the default doesn't fit. I hope this might be useful to others. lines 446>462 of the dist. .js

defaults = {
    bubbleLoc : 'left', // defaults to the right
    bubbleMax : '300', // max-width of error [was set in CSS but useful to set form-specific value
    bubbleMin : '80', // below this message set as 'Error'
}
//446   // Create the error window object which will be appear
    var errorObject = document.createElement('span');
    errorObject.className = this.options.errorTemplateClass;
    elParent.appendChild( errorObject ); // add error text [to get width]
    errorObject.innerHTML = error;  
    var pos, W, bubWide, bubbleMax, bubbleWide, bubOffset;
    pos = $( el ).position();
    if (pos.left<bubbleMin) { errorObject.innerHTML = 'Error'; }
    bubWide = $(errorObject).width(); // actual width of error span  
    if( this.options.display === 'bubble' ) {  // error display is bubble
    W = $( el ).outerWidth(true); // width of input element
    bubbleMax = this.options.bubbleMax; // bubbleMax set in defaults or form .js 
    if( this.options.bubbleLoc === 'left' ) { // put it left
    if (pos.left>bubbleMax) { bubbleWide = pos.left-10; bubOffset = pos.left-bubWide-28; } // space OK
    else { bubbleWide = pos.left-30;bubOffset = pos.left-bubWide-28; // narrow
    if (bubOffset<5) { bubOffset = '5'; }}
    $( errorObject ).css({ 'left':bubOffset +'px', 'top':pos.top+2 +'px', 'max-width':bubbleWide });
    $('.validetta-bubble').addClass('hidden');
    }
    else { // default right
    $('.validetta-bubble').addClass('hiding');
    $( errorObject ).css({ 'left' : pos.left + W + 4 +'px', 'top'  : pos.top+2 +'px' }); }
    }
    // elParent.appendChild( errorObject ); // NB. this has been set earlier to get size
    // errorObject.innerHTML = error ;
    // if errorClose is activated, create the element used to close the error window

Note: I have declared span html before positioning so as to get the size. There may be a tiny flicker but I feel it negligible. It could be temped into an off-screen element.

The other simple addition is a character test. This could be easily set in 'custom' but it seems that most inputs require some basic XSS test. This is a fairly relaxed regex and you can easily modify.

messages = { characters : 'Foreign characters',  },
        //RegExp for testing acceptable characters
        RCHARACTERS = new RegExp( /^[-.,_a-z A-Z 0-9\"\']+$/ ), 
// then down in 'validator..
        // Acceptable characters check
        characters : function( tmp ) {
            return RCHARACTERS.test( tmp.val ) || messages.characters;
        },

The other notable tweak has been a date function. There are SO many date permutations and I have done several mods but most are quite site specific. This one may have a general enough spread to be of use.
It first tests basic numeric format.
I am just using TODAY and have allowed for but not tested prior to 1970
Test - predate
Test span

//RegExp for testing date; dd-mm-yyy
DATEFORMAT =  new RegExp( /[0-9]{2}-[0-9]{2}-[0-9]{4}/ ),

messages = { 
testDate : 'Date: dd-mm-yyy',
testTime : 'This pre-dates {begin}',
testSpan : 'Exceeds the {dateSpan} {spanFormat} limit',
dateCompare : 'Departure pre-dates Arrival', },
dateExtent : 'Exceeds the {dateExtent} day limit' }
defaults = {
    dateStart : 'TODAY', // no date allowed before: TODAY || 4-digit year [eg. 2012 will check 31-12-2011]
                        // NB. year before 1-1-1970 will yield negative!
    dateSpan : '95', // days limit beyond dateStart [error msg: testTime]
    spanFormat : 'month', // dateSpan error shown as: day || month || year [error msg: testSpan]
                        // month maths = Math.floor (/31); so not so precise
    dateExtent : '21',  // days extent of stay; from arrival to departure
}
// Test date format
dateTest : function( tmp ) { var badDateNum; 
// simple numeric test
if (DATEFORMAT.test( tmp.val )==false) { return messages.testDate; }
// timestamp = milliseconds
if (defaults.dateStart=='TODAY') { var dateBegin = new Date();
var nowStamp= new Date((dateBegin.getMonth()+1)+","+dateBegin.getDate()+","+dateBegin.getFullYear()).getTime();}
// other than today
var yearReg = new RegExp( /[0-9]{4}/ );
if (yearReg.test(defaults.dateStart)==true) {
var nowStamp= new Date('12,31,'+defaults.dateStart).getTime(); // earliest start date
if (RNUMBER.test( nowStamp )==false) { alert('Admin, check var dateStart'); } }
// test user input
var userDate = tmp.val.split("-");   
var newDate=userDate[1]+","+userDate[0]+","+userDate[2]; // month day year
var userStamp = new Date(newDate).getTime(); 
if (userStamp<nowStamp) { return messages.testTime.replace( '{begin}', defaults.dateStart ); } // pre-dates
// test latest start date
var dateSpan = nowStamp + (defaults.dateSpan*24*60*60*1000); // (days) x hrs x mins x secs x milli
var spanFormat = defaults.spanFormat;
if (spanFormat=='month') { var dateSpanMath = Math.floor(defaults.dateSpan/31); }
if (spanFormat=='year') { var dateSpanMath = Math.floor(defaults.dateSpan/31/12); }
if (userStamp>dateSpan) { return messages.testSpan.replace('{dateSpan}', dateSpanMath)
.replace('{spanFormat}', defaults.spanFormat); } // exceeds dateSpan limit
},

I am not sure how useful this is so I have not extensively checked the above. I may have missed a few messages or defaults and such. I will see what, if any, feedback there is and could post some working examples if needed. Mostly my hope is to feed back into this field of generosity. A BIG thanks to you Hasan. Your work is appreciated.
arfa

Triggering error manually works, but the class is not changed

validettaObj.window.open.call(validettaObj, inputElement, errorMessage); this triggers error manually & it works very nice.
But the parent element still uses validetta-valid instead of validetta-error. Not big issue, but i think would be nice if it can be fixed from the library instead of patching it manually.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.