GithubHelp home page GithubHelp logo

contributte / live-form-validation Goto Github PK

View Code? Open in Web Editor NEW
59.0 14.0 24.0 140 KB

:no_entry: Nice client-side live form validation for Nette Forms.

Home Page: https://contributte.org/packages/contributte/live-form-validation.html

License: BSD 3-Clause "New" or "Revised" License

JavaScript 100.00%
nette forms validation javascript live

live-form-validation's Introduction

Website 🚀 contributte.org | Contact 👨🏻‍💻 f3l1x.io | Twitter 🐦 @contributte

Documentation

For details on how to use this package, check out our documentation.

Versions

State Version Branch
dev dev-master master
stable ^1.10.0 master

Development

See how to contribute to this package.

This package is currently maintaining by these authors.


Consider to support contributte development team. Also thank you for using this package.

live-form-validation's People

Contributors

bartko-s avatar dakorpar avatar f3l1x avatar h0w4rd avatar jangalek avatar janiczek avatar jelen07 avatar jzaplet avatar matej116 avatar pavelplzak avatar petrparolek avatar redhead avatar robyer avatar skybamar avatar zakrava 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

Watchers

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

live-form-validation's Issues

Použití s Grido s inline editací - Uncaught TypeError: Cannot read property 'hasError' of undefined

Zdravím,
začal jsem v aplikaci používat datagrid "Grido" pro nette a v gridu při "inline editaci", když mám nastaven sloupce setRequired a ve kterém lze hodnoty inline editovat, tak při prvním pokusu o uložení prázdné hodnoty mi to vypíše v consoli prohlížeče:
live-form-validation.js:488
Uncaught TypeError: Cannot read property 'hasError' of undefined

Jakmile se tento error objeví, tak při dalších pokusech o uložení prazdné hodnoty se errory neobjevují a správně se u kolonky objeví hláška, že pole je povinné. Udělá to vždy pouze jednou do doby než stránku reloadnu.

Aby se tento error neobjevoval, musím mít současně v aplikaci nalinkovaný soubor netteForms.js:
https://cdn.rawgit.com/nette/forms/v2.2.4/src/assets/netteForms.js

Já jsem ale někde četl, že netteForms.js jsou součástí té knihovny live-form-validation.js, a tak nevím, zda mám mít v aplikaci nalinkované oba soubory a je to tak v pořádku.

Lze to vyzkoušet na tomto example příkladu při inline editaci:
https://github.com/o5/grido-examples

Postup:

  1. nalinkovat do layoutu live-form-validation.js a zakomentovat původní "netteForms.js"
  2. spustit grido examples na presenteru "EditablePresenter.php", kde je umožněna inline editace
  3. udělat inline editaci ve sloupci "Surname": Na nějakou jeho hodnotu najet myší, podržet CTRL + doubleclick
  4. objeví se input pro editaci a obsah toho příjmení celý smazat a dát enter - v tomto kroku při snaze o uložení by se měla vedle inputu objevit hláška "Surname is required.", protože Surname má nastaveno setRequired('...').
    Ale neobjeví, objeví se viz. výše uvedený error. Další pokusy už chybu nehlásí a hláška se vedle inputu správně zobrazuje do doby, než se udělá reload celé stránky.

Error se tedy objevuje jen pokud mám v aplikaci "live-form-validation.js" a současně nemám "netteForms.js".

Předem se omlouvám, pokud to sem nepatří a pokud by to šlo nějak opravit, tak by to bylo skvělé.
Ale jestli je nutné mít v aplikaci nalinkovaný i "netteForms.js", tak potom je tedy vše v pořádku. Já jen myslel, že mi stačí "live-form-validation.js" bez toho netteForms.js.

Děkuji za případnou radu :)

RadioList, CheckboxList: validation error is removed only on selecting first item

When using RadioList or CheckboxList, the validation error goes away only if I select the first input. Also, the error spans doesn't populate, except the first one (but maybe this is intentional).

I'm using the default renderer:

$choices = array(
    'a'    => 'aaa',
    'b'   => 'bbb',
    'c'         => 'ccc'
);
$form->addCheckboxList('my_choices', 'Please select'), $choices)
    ->setRequired('Required field');

Am I doing something wrong?

Failed to execute 'insertBefore' on 'Node'

Hi,

I get this error on a regular bootstrap 3 form, Nette 2.4. Every field is wrapped by form-group, nothing special...

Everything happens on this line(306): parentEl.insertBefore(messageEl, el.nextSibling);

live-form-validation.js:306 Uncaught DOMException: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node.
    at Object.LiveForm.getMessageElement (admin/assets/js/live-form-validation.js:306:13)
    at Object.LiveForm.processServerErrors (admin/assets/js/live-form-validation.js:145:23)
    at Object.Nette.initForm (admin/assets/js/live-form-validation.js:1151:12)
    at HTMLDocument.<anonymous> (admin/assets/js/live-form-validation.js:1165:12)

Anybody else? Do you have some suggestions how to fix it?

Timing of setting custom options

I load live-form-validation by another JavaScript and I can't reliably control when this happens, so it's hard to set options after the script is loaded (using LiveForm.setOptions()). It would be great to have a callback that would be called when the script is loaded, so one could set custom options more reliably. Or perhaps using some kind of trigger on the form itself (or document?). Also, if the form ID could be passed to this callback/trigger it would be nice, as one could apply different options to different forms when having more than one of them on one page.

Sorry if there's something like this already built-in that I've missed.

Setting options without editing live-form-validation.js

As I see there's no way to set options without editing "live-form-validation.js". It would be handy to be able to set custom options outside the js file, so one could copy the original js to another project or use different options on forms within one project.

I can share my working code if you're interested. It extends LiveForm.options with a user-defined options object.

Little problem with form validation

How can I disable the check field if it is not filled?

LiveForm.setOptions({
            showValid: true,
            wait: 1500,
            messageErrorClass: 'text-danger',
});

EMAIL form:

$form->addText('email', '')
			->setType('email')
			->setRequired('Need email')
			->setAttribute('placeholder', 'Введите ваш email')
			->addCondition($form::FILLED)
			->addRule(Form::EMAIL, 'Nope :)');

Because I get the following
image

And need

image

Also... How can I display all the errors, if someone clicks the button "Register" and filled out all the fields?

Thank you, waiting for an answer!

toggle not work

$form->addCheckbox('check')
	->addCondition($form::EQUAL, true)
	->toggle('checked');
$form->addText('input')
	->setOption('id', 'checked');

This code work with original netteForms.js

Zamrznutí prohlížeče s verzí 1.4.2

U verze 1.4.1 se mi po kliknutí na tlačítko submit u formuláře chybové zprávy vždy vymažou vedle inputů a musím následně kliknout do prázdného inputu a potom kliknout jinam, aby se opět chybová hláška zobrazila, že pole je povinné.

Stáhnul jsem si tedy verzi 1.4.2. Tam chybová zpráva zůstane a nezmizí po kliknutí na tlačítko submit, ovšem u této verze se mi kousne vždy prohlížeč.

Postup:

  1. kliknu do prázdného pole a něco tam napíšu a kliknu pryč
  2. kliknu zpět do pole a vymažu ho a kliknu pryč nebo na jiné pole (následně se zobrazí chybová zpráva)
  3. odešlu formulář a prohlížeč zamrzne

V projektu mám nalinkované ještě knihovny:
jquery-1.11.3.min.js
nette.ajax-2.0.0

U input pole, když nastavím class=“validate-on-load”, tak se mi prázdné pole po načtení stránky neověří, ani u verze 1.4.1, tak i 1.4.2.

Nejsem si jist, zda něco dělám špatně nebo je to bug. Pokud to není bug, tak se omlouvám.

offset window scoll location on errors

Hello.
on submit when there's an error, the window location scrolls to show that field. but when i have a bootstrap fixed nav-menu then the menu obscures the field with the error. is there a way to set an offset for the scroll location (eg +100px lower)?

i think on v1.8.1 (which I'm using) its line 679: elem.focus();
a solution would be adding this line below that line with a variable for the offset (i'm not sure how browser compatible this is):
window.scrollTo(window.scrollX, window.scrollY - 100);// scroll above el in focus

thanks
Mike

Checkboxlist first input only enable

For checkboxlist i need it validation rules are present always onle fist enable chekbox. FIX code is

// Fix for CheckboxList - validation rules are present always only on ENABLE first input 
 if (elem.name && elem.name.match(/\[\]$/) && elem.type.toLowerCase() == 'checkbox') {
        	if(!elem.form.elements[elem.name].tagName)
			{
				for(var i=0 ; i <elem.form.elements[elem.name].length ; i++)
				{
					if(elem.form.elements[elem.name][i].disabled == false)
					{
						elem = elem.form.elements[elem.name][i];
						break;
					}
				}
        		}
         }

Why there is check for validity.valid if all rules came true?

There is check for validity.valid if elem.type === 'number' in the end of validateControl() function, which 1) has untranslatable error message and 2) is causing unexpected errors if there is condition rule and another rule after it.

More explanation for 2):

  • create input of type number

  • call ->addRule(Form::MIN, 0)

  • call ->addConditionOn( , )->setRequired();

  • call ->addRule(Form::MAX, 10)

  • let the form render, fill value bigger than 10

  • with this setup, the element has set both min and max properties, rendering validity.valid to be false for some value > 10. Calling validateControl() in this case would cause recursive call (because of the condition beeing true) and the condition for validity.valid in the end of nested call validateControl() fails.

Please corrrect me if I am wrong, but I am seeing the check for validity.valid useless.

Another font for icons

Hi,

i am tring change font of icon by class, but not working:

<script type="text/javascript" src="../system/vendor/nette/forms/src/assets/live-form-validation.js">
<script type="text/javascript">

    LiveForm.setOptions({
        messageErrorPrefix: '&nbsp;<i class="fa fa-exclamation-triangle" aria-hidden="true"></i>&nbsp;'
    });

</script>

Is right?
Thanks

E-mail validation

Hello, when using this live form validation, I've found, that validator validates e-mail [email protected] as valid. AFAIK domain y.z can not exist, also y.zz / yy.z (-:

Bootstrap 3 - input-group

There is an error in bootstrap 3 with input-group. Is it possible to change placeholder to only one element?

<div class="form-group">
   {label test /}
   <div class="input-group">
      {input test, class => 'form-control'}
      <span class="input-group-addon">m<sup>2</sup></span>
    {* sem se prida error message coz je spatne *}
   </div>
   {* spravne umisteni *}
</div>

Validator max & min not working at the same time

Both validators max and min are using the range validator, when the min and max validator are used at the same time. The range validator will fail on the first one since it is checking elem.validity.overflow/underflow flags and the error message of the first failed validator is issued.

This implementation of range validator would solve the issue:

range: function(elem, arg, val) {
		if (elem.type === 'number') {
			if ((elem.validity.rangeUnderflow && arg[0] !== null) || (elem.validity.rangeOverflow && arg[1] !== null)) {
				debugger;
				return false
			} else if (elem.validity.badInput) {
				return null;
			}
		}
		return Nette.isArray(arg) ?
			((arg[0] === null || parseFloat(val) >= arg[0]) && (arg[1] === null || parseFloat(val) <= arg[1])) : null;
	},

The only change is check for arg[0] !== null and arg[1] !== null.

How to pass custom variables with es6 module?

I'm using form validation with webpack this is how my main.js looks like, but none of the listed options doesn't work me. Is there anyone who use it with webpack as well? Or what I do wrong?

Validation works fine, but without the custom options.

import 'jquery';
import 'bootstrap';

import LiveFormValidation from 'live-form-validation-es6';

window.LiveForm = LiveFormValidation.LiveForm;
window.Nette = LiveFormValidation.Nette;

import 'nette.ajax.js';

$(function() {

  window.Nette.init();

  LiveFormValidation.setOptions({
    messageErrorPrefix: 'test 1',
  });

  window.LiveForm.setOptions({
    messageErrorPrefix: 'test 2',
  });

  LiveFormValidation.LiveForm.setOptions({
    messageErrorPrefix: 'test 3',
  });

});

Remove form's "hasError" property?

I just realized that since beginning is in code this this.setFormProperty(el.form, "hasError", true); call (in LiveForm.addError) and related checks.

It behaves like this:

  1. When first error is added, it sets form.hasError
  2. This form.hasError property is reset only when whole form is validated (when calling Nette.validateForm, e.g. on pressing submit)
  3. When form.hasError is true, new errors aren't notified (by alert()) and elements with new errors aren't focused anymore. See Nette.addError.

I don't understand what is it good for and I'm thinking about removing that altogether.

Can somebody tell me if that code is important/useful for some reason?

Inconsistent error display when validating CheckboxList control

The script does not reliably show the validation error for CheckboxList control. I've adapted the standard demonstration form, setRequired as follows:
$form->addCheckboxList('colors', 'Favorite colors:', [ 'red', 'green', 'blue', ])->setRequired("Enter your favourite colour");
only sometimes are the 'has error' class added to the parent div , and 'help-block text-danger' added to the message span.
i can sometimes get the error to show when I switch tabs, or when I complete other invalid items and again press submit. It appears to toggle the CheckboxList errors on and off each time I resubmit (with invalid data) when the data in other 'invalid' controls have been corrected.

the other control types show errors reliably/as they should.

If I remove 'live-form-validation.js' and use 'netteForms.js' the messages show reliably in the alert.
I'm using nette forms 2.4 (standalone) and jquery.min.js 1.10.2 on the page.

thanks for checking this.
Mike

Check if form is valid

Hello, thanks for lib otherwise I have a little problem to solve. I want to show loading after valid submit action how can I do that is there option to check if a form is validly filled up?
I want to something like this but now its always show loading even if form is not valid and live validation add errors to form inputs.

Thanks for response.

$('button[type="submit"]').on('click',function (e) {
                    if($(this).data('loading')){
                        if($(this).data('loading') == 'LOADING_FULL'){
                            $("#full_loader").show();
                        }
                    }
                });

RadioList validation error is removed only when you select the first list item

Steps to reproduce:

  • Add the radio list to the form.
  • Let the "please select some option" validation error occur (f.ex. submit the form without data).
  • Select some option, except the first one.
  • The error message is not removed.

The error message is removed only when the the first list item is selected.

The same issue has been described in the issue #15, but I'm not able to reopen it.

Affected versions: v1.9.0
When I downgrade to the v1.8.1 then it works as expected.

Roadmap - 2.0.0

  • Rewrite into TypeScript.
  • Provide better loading.
  • Write some tests.

Empty messages after hidden inputs

LiveForm generates a tag for message for hidden inputs even when I specify 'no-show-valid' and 'no-live-validation' class. Those tags are empty but have initial margin so it breaks my design.

Problem is in processServerErrors method where disabled classes are not checked. This function call method getMessageElement which create a tag for message. The processServerErrors method is called in Nette.initForm function.

My suggestion is as follows:

LiveForm.processServerErrors = function(el) {
	if (this.hasClass(el, this.options.disableLiveValidationClass))
		return;

Is there a validation success event?

I am trying to disable the Submit Input button with the following code:

jQuery('.form').submit(function(){
      jQuery(this).find('input[type=submit]').prop('disabled', true).val('Submitting...');
});

But when the validation is enabled and if it fails, it still changes the button to 'Submitting' after disabling it since it is called on every Submit event.

Is there some sort of event (like onValidationSuccess) I could use before running the above function?

Decimals

Hi,

if i have input[type=number] and want type decimal format number, validator returning "Please enter a valid value". I am also set: "step=0.5" and without change.

Required date picker

If I use any common JS date pickers, as Bootstrap datepicker lib, or jQuery UI date picker. And I have required date filed. Then validation error occures in a moment, I select date from the datepicker.

Resulting situation is, I have error state field, but value is set.

obrazek

Form can be posted, so it is not blocking. But it looks bad. And end users are still reporting it as an error.

showMessageClassOnParent not working

For example:

<div class="form-group col-md-6">
     {label mobile /}
     <div class="input-group">
          <span class="input-group-addon">+{$dialingCode}</span>
          {input mobile class=>'form-control'}
     </div>
</div>

snimek obrazovky 2016-02-16 v 10 51 42

Error message is inside .input-group but I set parent to .form-group

Manually created input validation.

Hi, I have malually created input, with required attr and data-nette-rules. But as I see, LFV did not create span for errors. I dont know why. Input looks like

<input name="products[]" type="text" class="form-control" required data-nette-rules='[{"op":":filled","msg":"Názov je povinná položka."}]'>

If I open brovser debugger there are som changes which comes from LFV. But I dont understant what it means. It looks like

<div class="col-xs-7 col-sm-10 lfv-error-parent">
    <div class="input-group">
        <input name="products[]" type="text" class="form-control" required="" data-nette-rules="[{"op":":filled","msg":"Názov je povinná položka."}]" data-lfv-initialized="true" data-lfv-message-id="_message">
        <span class="input-group-btn">
            <button class="btn btn-primary js-add-new" type="button" data-lfv-initialized="true" data-lfv-message-id="_message_1">+</button>
        </span>
    </div>
    <span id="_message" class=""></span>
    <span id="_message_1"></span>
</div>

It seems that it is ok. But it is not.

Error classes color

Hi, I would like to have span with class="help-block text-danger" colored to red. But Bootstrap needs to have .has-error class on parent element. As I founded out live-form-validation adds .has-error to input element which does nothing and span has black color. Am I doing something wrong?

Server side error message neni osetren

Kdyz mam server side validaci, zobrazi se error, tak live-form-validation s tim neumi pracovat a kdyz zmenim input, aby to vyvolalo jeste live validaci, tak tam mam dva error message a ten server side to nechce smazat.

Nejdriv jsem to chtel cele prepsat z id na class, ale nakonec jsem skoncil u jednoduche podminky pridane do getMessageElement pred if (!error) nasledujici:
if(!error) {
error = el.parentNode.getElementsByClassName(this.options.errorMessageClass)[0];
}

Forkovat kvuli pull requestu mi prijde divne.

Using Nette.validateForm for check only

First of all, thank you for this neat library, it works just great! However, there is a small issue I stumbled upon.

I would like to use Nette.validateForm function which accepts onlyCheck flag as a second argument to determine, whether it should show error message or just return a boolean indicating the form's current validity.

It seems that parts of the original nette-forms code were removed so it always triggers error messages.

I am currently importing original nette-forms to utilize the function in my use-case, but that seems as a wrong approach to me as both live-form-validation and nette-forms use globally scoped Nette variable.

What would be the correct approach if I just need to check whether the form is valid on client-side without triggering any error message?

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.