Code Monkey home page Code Monkey logo

nod's Introduction

Nod v.2.0.13

Frontend input validation

Practical info

  • Introduction and Examples: nod introduction
  • License: MIT.
  • npm: npm install nod-validate
  • Dependencies: None.
  • Browser support: Chrome (newest) / FF (newest) / ie9+.
    • Please help me test in ie (9 and up). I have very limited access to windows machines.
  • Backwards compatibility: ver. 2 is not compatible with previous versions.

Example

Cloning the project, and checking out the examples is the best way to go. But here are some basic stuff to give you and idea and get you going.

<form action=''>
    <label>
        <span>Name</span>
        <input type='text' class='name'>
    </label>
    <label>
        <span>Email</span>
        <input type='text' class='email'>
    </label>
    <label>
        <span>Email again</span>
        <input type='text' class='email-again'>
    </label>
    <label>
        <input type='checkbox' class='terms'>
        <span>I agree to terms &amp; conditions</span>
    </label>
    <button class='submit-btn' type='submit'>Sign up</button>
</form>

A basic sign up form. Let's add some validation.

var n = nod();

// We disable the submit button if there are errors.
n.configure({
    submit: '.submit-btn',
    disableSubmit: true
});

n.add([{
    selector: '.name',
    validate: 'min-length:2',
    errorMessage: 'Your name must be at least two characters long.'
}, {
    selector: '.email',
    validate: 'email',
    errorMessage: 'That doesn\'t look like it\'s a valid email address.'
}, {
    selector: '.email-again',
    validate: 'same-as:.email',
    errorMessage: 'The email does not match.'
}, {
    selector: '.terms',
    validate: 'checked',
    errorMessage: 'You must agree to our terms and canditions.'
}]);

Documentation

Adding input fields

nod is a factory, which spits out instances of nod when called (no parameters).

var myNod = nod();

Elements can then be added to it via objects (or an array of objects) describing each.

myNod.add({
    selector: '.foo',
    validate: 'presence',
    errorMessage: 'Can\'t be empty'
});

The selector property works much like a jquery selector (in fact, if jquery is available, it will use jQuery to do the work). You can throw most anything at it. A simple css type selector (like in the example above), a list of selectors, raw dom elements, jQuery elements, even NodeLists.

The validate property can be a string with the name of the function you want to validate the input of the element with (there should be a list somewhere on this page), or your own function (see next example), a RegExp, or you can directly extend nod.checkFunctions with your own function and reuse it throughout your website.

The errorMessage is a string containing the error message (in case the validation fails) that will be shown behind the field.

myNod.add([{

    // Raw dom element
    selector: document.getElementById('foo'),

    // Custom function. Notice that a call back is used. This means it should
    // work just fine with ajax requests (is user name already in use?).
    validate: function (callback, value) {
        callback(value % 2 === 0);
    },

    errorMessage: 'Must be divisible by 2'

}, {

    // jQuery element
    selector: $('.bar'),

    // EegExp
    validate: /hello/g,

    errorMessage: 'Input must say hello'

}]);

triggeredBy

There is one more setting you can add; triggeredBy. This is a selector for another element (it will only match the first matched element), where changes will also trigger a check on the current element. Example:

// Feel free to use `nod.getElement` and `nod.getElements` to get the row dom
// element(s).
var someCheckbox = nod.getElement('.some-checkbox');

myNod.add({
    selector: '.some-input',
    // You could also just add the raw dom, just created above.
    triggeredBy: '.some-checkbox',
    validate: function (callback, value) {
        if (someCheckbox.checked) {
            callback(value.length > 0);
        } else {
            // If checkbox isn't checked, then it doesn't matter if .some-input
            // is filled out.
            callback(true);
        }
    },
    errorMessage: 'If the checkbox is checked, then we need your name'
});

triggerEvents

By default, nod listens for input, change, and blur events; however you can add your own as well. This can be done with triggerEvents like so:

myNod.add({
    selector: '.foo',
    validate: 'presence',
    errorMessage: '...',
    triggerEvents: 'keyup' // can also be an array of event names
});

This is especially helpful if you manually need to trigger a check, or if you're validating a normal element with contenteditable='true'.

If you are using jQuery and need to update the element by other means, then calling $('.foo').trigger('change'); won't work out of box. You have to manually tell nod that jQuery is available and where to find it before it will listen for jQuery events:

myNod.configure({
    jQuery: $
});

After that is configured, elements being added will listen for the jQuery change event.

defaultStatus

By default, nod considers an element unchecked until a user types something into it (or in some other way triggers a check). You can change this, by adding a defaultStatus:

myNod.add({
    selector: '.foo',
    validate: 'presence',
    errorMessage: '...',
    defaultStatus: 'valid'
});

This is useful because an "unchecked" element will disable a submit button, whereas a "valid" button won't.

Consider this example. First some html with a page where I can change my name (it's currently "John Doe").

<label>
    <span>Your name</span>
    <input type='text' value='John Doe' class='name'>
</label>

<button type='submit' class='submit-name'>Change your name</button>
var myNod = nod();

myNod.configure({
    submit: 'submit-name',
    disableSubmit: true
});

myNod.add({
    selector: '.name',
    validate: 'presence',
    errorMessage: 'You need a name.',
    defaultStatus: 'valid' // Without this, the submit button would be disabled
});

Removing input fields

Once added, you can also remove an input field from being checked. It's done much like you'd expect (I hope).

myNod.remove('.foo');

If '.foo' matches more than one element, they will all be removed.

Some configuration

Each instance of nod can be configured to suit specific needs. This is done either via

myNod.configure({
    delay: 400
})

or when creating the instance

var myNod = nod({
    delay: 400
});

Below, I will walk you through each of the options available.

Classes

We can change the classes of both the "parent" and the "error span". I'll go through each referring to this html:

<div class='group'>
    <label>
        <span>What's the meaning of life?</span>
        <input type='text' class='foo'>
        <!--
            error span gets added here:
            <span class='nod-error'><%= errorMessage %></span>
        -->
    </label>
</div>
Parent

By default, the label (the parent of the input) will have the class 'nod-success' or 'nod-error' when the element is checked. These class names can be changed via nod.configure like so:

myNod.configure({
    successClass: 'myNewSuccessClass',
    errorClass: 'myNewErrorClass'
});

If you want, instead, that the "parent" isn't its immediate parent, but something further out, you can tell nod to search for a parent with a class like so:

myNod.configure({
    parentClass: 'group'
});

Notice that the error span that the error span always gets appended to the "parent", in the above example, it would now be added after the </label> and not inside it.

Error Span

The class of the error message can also be changed:

myNod.configure({
    successMessageClass: 'myNewMessageSuccessClass',
    errorMessageClass: 'myNewMessageErrorClass'
});

However, nod doesn't show a message behind the input field when it's valid. You have to set that by the configure method as well:

myNod.configure({
    successMessage: 'Well done!'
});

The message will be shown after every valid input field in myNod.

Changing the position of the error span is a bit more tricky (unless you do it by changing the parentClass, see above). You can, specifically for each element tell nod which dom element to use as the error span. See setMessageOptions below.

no DOM mode

If you want to prevent nod from inserting error spans in your dom, but rather take care of showing/hiding error messages yourself, you can pass in a noDom property in configure:

myNod.configure({
    noDom: true
});

nod will then instead fire an event named nod.validation on the actual element that you can listen for:

function myFunc (event) {
    console.log(event.detail);
}

myElement.addEventListener('nod.validation', myFunc, false);

The content of event.detail should be enough for you to handle the error.

Delay

By default nod waits 0.7 seconds before display an error message. This is so the user isn't being bothered with error messages about something that he or she is not done typing. This delay can be changed via configure method:

myNod.configure({delay: 300});

Notice, however, that this delay only deals with the time before showing an error message. Removing it will happen instantly, and there is currently no way to change that.

Disable submit button

You can disable the submit button, until all added elements are considered valid. This is done like so:

myNod.configure({
    submit: '.submit-button',
    disableSubmit: true
});

However, be aware, that forms can often be submitted by hitting enter, and a disabled submit button will not do anything to prevent that (see next section).

Prevent Submits

If you tell nod about the form and set preventSubmit: true in configure, then it will prevent submits entirely, until all added elements are considered valid.

If an error is detected (and submition prevented), then we show error messages for all non-valid elements, and focus on the first of those elements.

myNod.configure({
    form: '.myForm',
    preventSubmit: true
});

I should caution the use of this however, as it is hard to get it right in every case (from me, the designer's perspective). So test it well, and make sure it is working correctly in your use case. The last thing you want (I assume) is to prevent your users from submitting your form entirely.

Tap into the checks

You can "tap" into the internals, and get updates about the state of your elements by adding a "tap" function via configure.

myNod.configure({
    tap: function (options) {
        console.log(options);
    }
});

This will give you a lot of calls to your console (basically one, per key press). The options argument contains various properties used internally and is very likely to change (that's why it's an object and not 5 different arguments), but the most useful are probably options.element, options.result, and options.validate.

setMessageOptions

You can specifically for each element tell nod which is its parent and which dom element to use as its error span:

myNod.setMessageOptions({
    selector: '.foo',
    parent: '.myCustomParent',
    errorSpan: '.myCustomErrorSpan'
});

Notice, that the "parent" (despite its name) does not have to strictly be a parent. There is also no need to set both the parent and the message.


These settings are especially useful when working with radio buttons. Have a look at examples/05-radio-inputs.html to see an example of how it is used to avoid showing an error message behind every single radio button, but rather show just one at the end of the list.

Manually checking validity

nod currently exposes two functions for for manually checking validity of the elements. One for checking all elements (this is the same used, to enable/disable the submit button internally:

myNod.areAll('unchecked');  // Returns a boolean
myNod.areAll('valid');
myNod.areAll('invalid');

// Safer way to call it:
myNod.areAll(nod.constants.UNCHECKED);

And you can also query one element specifically like so:

myNod.getStatus('.foo'); // 'unchecked', 'valid', or 'invalid'

If you want to get the error message as well, you can call it like this:

myNod.getStatus('.foo', true); // {status: 'invalid', errorMessage: 'some error msg'}

If you need to check them up against something, I suggest you use nod.constants to do so. Like this:

if (myNod.getStatus('.foo') === nod.constants.VALID) {
    // Do something
}

Force nod to perform a check

nod provides you with a method: myNod.performCheck() which forces nod to run through each element and checks its validity. This can be useful when updating the value manually by JavaScript.

Alternatively, you can also pass in a selector, or the raw dom elements, to indicate that you only wish to force a check on those:

myNod.performCheck(['.foo', '.bar']);

List of check functions.

Most should be pretty self explaining.

[String] should be replaced with whatever string you feel is appropriate. See examples below (or in the examples folder).

  • "presence"
  • "exact:[String]"
  • "contains:[String]"
  • "not:[String]"
  • "min-length:[Number]"
  • "max-length:[Number]"
  • "exact-length:[Number]"
  • "between-length:[Number]:[Number]"
  • "max-number:[Number]"
  • "min-number:[Number]"
  • "between-number:[Number]:[Number]"
  • "integer"
  • "float"
  • "same-as:[String]" (A css type selector)
  • "one-of"
  • "only-one-of"
  • "checked" (For checkboxes only)
  • "some-radio" (For a group of radio buttons)
  • "email" (Uses the RFC822 spec to check validity)

A few examples of how to use the above list

myNod.add({
    selector: '.foo',
    validate: 'exact:foo'
    errorMessage: 'You must write exalctly "foo" in the input field'
});

All are accessed through the validate property of adding an element.

Some more examples:

// ...
{
    selector: '.foo',
    validate: 'between-length:2:4',
    errorMessage: 'Must be between 2 and 4 characters long'
}
// ...
{
    // This will check that at least one of the inputs matched by the selector
    // has a value.
    selector: '.phone-number-inputs',
    validate: 'one-of',
    errorMessage: 'You need to type in at least one phone number'
}
// ...
{
    // You can add validate functions in a list. Just remember to also have
    // errorMessages be a list with corresponding texts.
    selector: '.foo',
    validate: ['email', 'max-length:8'],
    errorMessage: ['Must be a valid email', 'Your email is too long. Sorry.']
}
// ...
{
    selector: '.foo',
    validate: 'same-as:.bar',
    errorMessage: 'Must be the same as in .bar'
}

one-of, only-one-of, and some-radio all match on their selector. same-as is called as same-as:[selector].

Extending nod.checkFunctions

You can extend the available check functions in nod like this:

// Note that this is the general `nod` function. Not a particular instance.
nod.checkFunctions['divBy2'] = function () {
    return function (callback, value) {
        callback(value % 2 === 0);
    };
};

This function can then be reused:

myNod.add({
    selector: '.foo',
    validate: 'divBy2',
    errorMessage: 'Must be divisable by 2'
});

We can also use arguments when setting up the function. Like so:

nod.checkFunctions['divByX'] = function (x) {
    x = parseInt(x, 10);

    return function (callback, value) {
        callback(value % x === 0);
    };
};

And to define "x", we use it like so:

myNod.add({
    selector: '.foo',
    validate: 'divByX:3',
    errorMessage: 'Must be divisable by 3'
});

If you need more arguments, you just separate them with ":".

validate: 'myFunc:a:b:c:d:e'

A little more comprehensive example. Say we want to make a game where the user has to add up numbers. We have some html:

<div>
    <span class='a'>21</span> +
    <span class='b'>13</span> =
    <input type='number' class='result'>
</div>

And let's see some check function:

nod.checkFunctions['calc'] = function (a, b) {
    var strA = nod.getElement(a).innerHTML,
        strB = nod.getElement(b).innerHTML,
        result = parseInt(strA, 10) + parseInt(strB, 10);

    return function (callback, value) {
        value = parseInt(value, 10); // values are always strings

        callback(value === result);
    };
};

// And let's use it
myNod.add({
    selector: '.result',
    validate: 'calc:.a:.b',
    errorMessage: 'Wrong! Don\'t you know math?'
});

nod's People

Contributors

casperin avatar chall8908 avatar luishdez avatar mattiaocchiuto avatar singingbush 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  avatar  avatar  avatar  avatar

nod's Issues

IE compatibility

How can I make this plugin IE8 compatible? Thanks in advance.

Need help with ajax check

Hi there and thanks for your great plugin.

I have trouble get the ajax check working. My jQuery Version is 1.8.2 and here are my files:

ipcheck.php

<?php

$ip = $_GET['address'];

if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
  echo "true";
}
else {
  echo "false";
}

?>

serversubmission.php

var ipCheck = function( value ) {
    $.get('ipcheck.php', { address: value });
};

var metrics = [
[ '#inputAddress', ipCheck, 'Not a valid ip address' ]
];

$( '#serversubmission' ).nod( metrics );

The ipcheck.php answeres true but the plugin always tells the input is not valid. Am i doing something wrong here?

Missing License

This looks great, and we'd like to use it in our project. However, our CTO requires that we have a proper license to ensure we can legally use it.

If you have no preference, might I suggest the MIT License which is quite popular in many open source projects?

A simple addition to the JS file would do the trick:

// May be freely distributed under the MIT license.

suggestion for an optional validation.

Meaning that if you send the form, you might get the message 'are you sure you want to leave this blank?'. Probably more of a reminder to not leave the field blank, but it can still get sent that way.

I know can be done fairly easy with normal script, but maybe it fits quite well in this plugin.

cannot submit form

I have tried for the past 3-4 hours to figure out how to submit a form after validation but could not do it. I cant believe its this hard to figure out. Could someone share a working example please.

Here is my code that does not work in case someone can glance at it.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>tester</title>
    <link href="lib/bootstrap-combined.min.css" rel="stylesheet">
    <script src="lib/jquery.min.js"></script>
    <script src="lib/bootstrap.min.js"></script>
    <script src="nod.js"></script>
</head>
<body>
<div style="width: 300px; margin:0px auto">
        <form id="myForm" action="nod.php" method="post">
            <h3 class="form-signin-heading">Please sign in</h3>
            <input type="text" name="username" id="UserID" placeholder="User Id">
            <input type="password" id="Password" name="password" placeholder="Password">
            <br>
            <button class="btn btn-primary" type="submit" name="submit">Login</button>
        </form>
</div>
<script>
var metrics = [
    [ '#UserID', 'presence', 'User ID is Required' ],
    [ '#Password', 'presence', 'Password is Required' ],
    [ '#Password', 'min-length:4', 'Must be at least 4 characters long' ]
];
 $( "#myForm" ).nod( metrics);
</script>

</body>
</html>

Thoughts about Unit testing and Continuous integration with Travis?

That would be great.

BTW I've register the library in bower now you are visible

$ bower register jquery-nod git://github.com/casperin/nod.git
Registering a package will make it visible and installable via the registry.
Proceed (y/n)? y
registered jquery-nod to git://github.com/casperin/nod.git
work at imac-work in ~/Desktop
$ bower search jquery-nod
Search results:

  - jquery-nod git://github.com/casperin/nod.git

ajax form

This is a good project, but i have a problem with form ajax.
To submit the page is reloaded onto itself, even though I specified event.preventDefault(); on my button.

Validation activated after select control is filled

Using Laravel if you fill one select control like this:

<select class="span12 someclass" name="sitio" >
      <option>Select One</option>
    @foreach($rows $k => $v)
        <option value="{{ $k }}">{{ $v }}</option>
       @endforeach
</select>

The validation is activated. Even if you fill by hand it activates even if there's no change on the control. Look at the fiddle http://jsfiddle.net/AyYBT/1/

If you try to select an entry buy keeps the "select one" option, the activations is triggered. Click the control and then clicks on the page and the message is showed.

Ajax email uniqueness validation

var email_valid = function (value){
var flag=0;
$.ajax({
url: "/users/valid",
type: "POST",
data: {"email": value, "_csrf": "#{csrf_token}"},
success: function(data){
flag=1;
}
})
return flag;
}

[ '#email', (email_valid),' Email is in use. Please try another one.']

It doesn't work. How can i accomplish this?

Submit blocking with multiple submit buttons

In some instances a form with have multiple submit buttons, like an ASP.NET webform.

Some buttons should set off the validation and the form shouldn't submit if the validation fails, other buttons should be able to submit without validation.

The main Jquery Validation plugin handles this by allowing form submission if the button has the class "cancel":

http://docs.jquery.com/Plugins/Validation/Reference
Skipping validation on submit

To skip validation while still using a submit-button, add a class="cancel" to that input.

I was hoping that the submitBtnSelector property would work similarly, where the valifation would only occur if the form was submitted with a button that matches that selector, but currently and submit on the page fires off the validation.

I would suggest either change the onsubmit handler to check for a match with the submitBtnSelector as the event target, or implementing a filtering class like the original validation library.

Class of inputs parent div won't update when an error is detected.

Hi there,

Thks for this very useful script.
I'm experiencing a problem with adding the bootstrap error class to the parents div of my form inputs : it won't get added.
Msgs are displayed alright but without the "error" addition to .control-group
see the Contact Form in the footer at http://prototypes.lafabriquedureel.fr/tlabstudio/index-2.html
I commented out the keyup DelayedCheck from your script (behavior doesn't suit my need : blur / change events are quite enough in my opinion). But the problem was already occuring.
My HTML markup is OK and i didn't alter the default settings for groupClass or groupSelector.

Any clue on what might be wrong ?
Again : thx

Valid message

I think it would be great if we could show the user a message if the validation of a field was ok. On a lot of websites you see green checkmarks etc. if a username is still available and so on. It would simply be an additional message in the metrics array.

Compatible with Twitter Bootstrap 3?

I love this plugin, its exactly what I'm looking for.

But it doesn't seem to be applying the styles no matter what I do so I must ask, is this Twitter Bootstrap 3 compatible?

I know its loaded as my site is using it heavily so I'm guessing the plugin is looking for an older class.

conflicts with other libs

  1. Wrap entire lib in jQuery wrapper so it works even when $ isn't the jQuery caller
  2. Don't trigger 'toggle' on an element. It's too general. trigger 'nod_toggle' or something instead.

Allow to check if the form is valid programatically

Currently there seems to be no way to programatically check if a form is valid. I need to do this because I have multiple forms that depend on each others (each on a different tab).

The ideal interface should be something like this: var hasErrors = $("#myform").nod().formIsErrorFree(); This would be quite easy to do if you associate the Nod class to the form and just return it when $.nod() is called without args, in a similar way other jQuery functions work.

Error Cannot set property '__nod' of undefined

I do not know JavaScript well, so I'm missing something that I think is simple.

I am getting the following error:

Uncaught TypeError: Cannot set property '__nod' of undefined

Whenever I try to add two forms for validation. If you remove a form and leave only one, everything works.

The code I'm trying to run is as follows:

var register_form = [
    ['#register_user_name', 'presence', 'Seu nome não pode ficar em branco'],
    ['#register_user_email', 'presence', 'Seu e-mail não pode ficar em branco'],
    ['#register_user_email', 'email', 'Digite um e-mail válido'],
    ['#register_user_password', 'presence', 'Sua senha não pode ficar em branco'],
    ['#register_user_password_confirm', 'presence', 'Sua senha não pode ficar em branco'],
    ['#register_user_password_confirm', 'same-as:#register_user_password', 'Suas senhas não combinam'],
    ['#register_user_phone', 'between:10:11', 'Telefone deve ter entre 10 e 11 dígitos incluindo o DDD.'],
    ['#register_user_twitter', 'min-length:3', 'Twitter deve ter no mínimo 3 caracteres'],
    ['#register_user_tos', 'presence', 'Aceitar os termos de uso é obrigatório.']

];

$("#register_form").nod(register_form);

var contact_form = [
    ['#contact_name', 'presence', 'Seu nome não pode ficar em branco']
];

$("#contact_form").nod(contact_form);

Anyone know why and how to fix it? :(

Errors happened when trying to rebind the plugin

I'm trying to rebind the plugin because I've some hidden inputs that I need to validate only in the case when a checkbox is checked, and I've tried rebinding the plugin when I show these inputs, the problem is that you're creating a new instance of the plugin each time when I call $(selector).nod();

Thanks for this awesome plugin, please keep my comment in mind and fix the problem if possible.

Best regards

All fields show validation messages on first field exit??

Hi,

I am currently developing a grails application and I use bootstrap for the front end UI. I now want to incorporate this plug-in in order to take advantage of client-side validation. The issue I am having with the code below is that when I exit any on of the fields that has validation on it the messages show up next to all the fields that have validation. I want to be able to only show the validation message for that field they exited and not the others, here is my code:

<form id="ex4" class="form-horizontal">
  <p>Leave at least one number</p>
  <div class="control-group">
    <label class="control-label">Home</label>
    <div class="controls">
      <input type="text" id="ex4a_home">
    </div>
  </div>
  <div class="control-group">
    <label class="control-label">Work</label>
    <div class="controls">
      <input type="text" id="ex4a_work">
    </div>
  </div>
  <div class="control-group">
    <label class="control-label">Mobile</label>
    <div class="controls">
      <input type="text" id="ex4a_mobile">
    </div>
  </div>
  <div class="controls">
    <button type="submit" class="btn">Call me</button>
  </div>
</form>
<script>
  var metrics = [
    [ '#ex4a_home, #ex4a_work, #ex4a_mobile', 'one-of', 'Add at least one number' ]
  ];
  $( '#ex4' ).nod( metrics );
</script>

Am I doing something wrong? Thanks in advance for the help.

Does not work properly with predefined values.

Hello,

I use predefined value in a form and it looks like it will be skipped by NOD.

Steps to reproduce:

I have added a value into the first form from examples for NOD:

  <form action="" id="a" class="form form-horizontal">
    <div class="control-group">
      <div class="control-label">
        <label>Your age</label>
      </div>
      <div class="controls">
        <input type="text" id="a_age">
      </div>
    </div>
    <div class="control-group">
      <div class="control-label">
        <label>Email</label>
      </div>
      <div class="controls">
        <input type="text" id="a_email" value="[email protected]">
      </div>
    </div>
    <div class="controls">
      <button type="submit" class="btn">Go!</button>
    </div>
  </form>
  • Put cursor in "Your age" field and input a digit.
  • Wait for dalay

Actual result:

Submit button is disabled.

Expected result:

Submit button is enabled.

Thanks,
Anton

Change of behaviour in 1.0.4

The commit 4707988 introduced a change of when the checks are run.
Previously, checks on a form field are only run once the user placed the cursor inside, made a change, or moved the cursor outside again. Plus, when the user submitted the form.
Now, the function formIsErrorFree calls runCheck on all listeners if their status is null.

You can see that change on example 3:
http://casperin.github.io/nod/ (here, 1.0.3 is still used)
http://jsfiddle.net/vb2hZ/ (this uses the latest version, 1.0.5)

If I enter "foo" (or anything else), it now immediately highlights an error on the dropdown, because I haven't selected a value there.
A more complex form that is empty at initialization, would be full with error messages before the user even has the chance to enter values.

I really don't like this behavior and have reverted back to 1.0.3 in my application. I understand that formIsErrorFree is used to programmatically check whether the form is valid and it that case it is totally valid to check all the form fields at once. But this should not be used internally whenever a change is triggered on a field.

Implement checkboxes

There is currently (I think) no way to add validation for checkboxes.

--- Scrap that. I meant radio buttons...

Checkbox Validation

Hi, Is it possible validate checkboxes? Tried using the 'one-of' metric but it's not working.

I have five checkboxes and only require that the user select one in order to submit the form.

same-as: not validating for empty field

Hi,

I tried to use nod with the validator same-as:

var metrics = [
[ '#repeatPassword', 'same-as:#inputPassword', 'Not matching' ]
];

Unfortunately, this dosent work right. If the first inputPassword contains some string value and the second repeatPassword is empty, the validation dosent produce any error. In this case I can freely submit the form.

Server-side validation

Really like this plugin and its simplicity. But I would like to integrate some server-side validation using jQuery.ajax ... is there a way to get this done? I know that you can validate with a function, but this won't work if you are waiting for an reply to the ajax request.

Validating elements outside of a form

I have a web application that has multiple AJAX jQuery forms on a single page, and there are a few input fields outside these forms that they share. On submit of a form, some Javascript runs to dynamically populate an HTML table. My question is: is there a way to create a Nod instance on a form, and validate fields outside of it? Or can I make several Nod instances on the <body> element that use different metrics to validate the different forms?

if that then this

i have two doubts here if you can answer the first one then second does not exist anymore, i can solve that easily.

I have two fields url and "url label", what i want is either user can enter url or both but not only the label.. i have written the function for that like

[ '#callToActionLabel,#callToActionURL', ( function() { return !(!($('#callToActionURL').val()) &amp;&amp; $('#callToActionLabel').val())} ), 'provide the url first' ]

it works great but if user first enter the label it will validate as false, and then if user enters the url it works fine but do not remove the error message from the label and do not enable the submit button..

can i manually call the validate on the label after calling url so it will revalidate the label?

Ajax checking

Hey Casperin,

great work and a really clean approach to forms validation! Your sample for ajax checking does not seem to work properly with v 1.0.2 due to the async nature of the $.get() request, or am I overlooking something? After trying to get server-side validation to work and looking into your source a quick fix for at least the documentation could be

var checkFn = function(value) {
return $.trim($.ajax({type: "GET", url: 'check_email.php', data: value, async: false}).responseText);
};

Best regards, Nicolas

Naming

Ever thought of renaming this library? "nod.js" is so similar to "node.js" that it's very hard to find it on Google etc. even when using the correct name.

It should not validate if value is empty

This change is a little hard because it will break backwards compatibility , but I think it should be done as soon.

If you check other libraries you will see this behavior.

If you have optional fields Eg: an optional email how do you will validate this ? because it looks that all validations force a not empty validation.

same-as: not validating for empty field

Hi,

I tried to use nod with the validator same-as:

var metrics = [
[ '#repeatPassword', 'same-as:#inputPassword', 'Not matching' ]
];

Unfortunately, this dosent work right. If the first inputPassword contains some string value and the second repeatPassword is empty, the validation dosent produce any error. In this case I can freely submit the form.

Forms correctly filled are not submitting

Hi,

When a form is correctly filled and I click on the submit button (input element with type="submit") the form is not sent. Even if silentForm is set to FALSE doesn't work. Console doesn't give any error and I tried as well with other browsers.

Regards.

Enter key bypasses form validation

Pressing the enter key inside a form will cause it to bypass Nod validation rules and submit. I've tested this behavior in IE 9, Safari 6 and Chrome 25. The form behaves as expected when you only use the Submit button.

validating not mandatory fields

I have some fields that needs validation like phone number. That field is not mandatory but if used it should be validated. Is it possible to validate field only if it have value?

Disable/Destroy NOD validation for a form

Current version of NOD validation upon creating it, doesn't provide a way to remove its validation checks on the forms. i.e., there is nothing like a destructor. Compelled by such requirement, I had to fork your repo and had to add a feature to accommodate it.

It is useful to dynamically reassign new validations to the form upon certain events.

https://github.com/simtron/nod is the forked repository.

Alert validation msg

Hello,

How can I alert the validation message as well as continue to display on screen.
Thanks for help.

Validate on exit formfield (Fire validate on/after tabbing?)

How do I get the validations to fire as soon as I "exit" the field, meaning if I get into the field through a tab, and then "leave/exit" that form field, the validation should be fired.

It works perfectly if I click inside a field.

Nice plugin btw 👍

How to clear error messages inserted by nod

I have form in modal window.
First thing i don't like is that form is checked for errors on close button. Is it possible to turn that of. I would like to evaluate form only on submit and while inserting data.
On open modal I clear all fields so form is empty but I didn't find the way to clear error messages inserted by nod.
Example.

  1. open form (click on add new)
  2. nothing is inserted and click close ... form is evaluated and all is red ... modal is closed
  3. open form again ... all is red

hope there is a solution.

Radio group support.

First, thanks for creating this great plugin!

I'm trying to bind Nod to a few radio button groups. After looking through the source I was under the impression that this would work.

Nod Metrics:
[ 'input[name=first-apartment-options]', 'presence', '' ]

HTML Markup:

    <div class='row-fluid'>
      <div class='span6'>
        <div class='control-group'>
          <label class='control-label required'>First Apartment?</label>
          <div class='controls check-radio'>
            <label class='radio inline'>
              <input name='first-apartment-options' type='radio' value='yes' />
              Yes
            </label>
            <label class='radio inline'>
              <input name='first-apartment-options' type='radio' value='no' />
              No
            </label>
          </div>
        </div>
      </div>

However nod_msg never gets applied to anything and the validation fails.
Any Thoughts?

Consider adding 'presence-if'

Consider adding a metric 'presence-if'

use case:
you have a select field "school": [ "UCLA", "Harvard", "Yale", "other" ] and a text field called "other_school". the "other_school" field would need "presence" only if the value for "school" is "other"

[ 'input[name=other_school]', 'presence-if:select[name=school]:other', "You must supply the name of your school if it's not in the list" ]

changing NOD selector dynamically

I spent entire day try to solve this problem, but seems can't find the remedy.

This is my program skeleton http://jsfiddle.net/zhwzY/

From the snippet, I try to make variable "form_input" to switch to a new value depend on the checkbox. With this method, I can prevent NOD from validating unecessary input. But the variable is not updating to the new value.

Please help.

P/s : No external reference to the NOD library in jsFiddle.

How to stylize error messages using css ?

This is my first use of a Jquery plugin, so please excuse me if I seem a little off-topic.
I'd like to know how to stylize errors messages displayed par Nod using css or others, same question for the input boxes who display such messages.

Thank you.
Regards

jQuery noConflict issue

The jQuery object is being passed into the IIFE wrapper and being aliased to $, however this aliased variable is only used when defining the jQuery plugin and the global jQuery is being used throughout the rest of the code. This is fine but when jQuery.noConflict(true) is executed this variable is no longer available.

Is it possible to make use of the aliased variable so we don't run into this issue?

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.