Giter Club home page Giter Club logo

validate.js's Introduction

validate.js's People

Contributors

abishekrsrikaanth avatar alanhietala avatar andymantell avatar artshpakov avatar benbrowning avatar brenopolanski avatar cballou avatar deefour avatar diegomorales avatar eheitman avatar fabiowitt avatar i-like-robots avatar ikr avatar jhnns avatar kkirsche avatar mkanev avatar mpchadwick avatar mrgrain avatar navruzm avatar nulldivision avatar pbellerive avatar porada avatar rickharrison avatar samccone avatar sammylupt avatar tajo avatar theraot avatar thibaudcolas avatar unkas avatar websiteduck 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  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

validate.js's Issues

Submit event firing on error.

I am having an issue with my code and can't seem to get it to work properly. When I submit the form, the error function is issued and the HTML is updated-- but right after, it submits the form and I am not sure what I am doing wrong.

<?php

    if(!is_array($form)){
        ?><p>Sorry but the form you requested is not available, please go back to the <a href="?p=dash">dashboard</a> and try again.</p><?php
    }else{ ?>
        <ul id="messages"></ul>
        <form action="?p=form&f=<?php echo $_GET['f']; ?>" method="post" name="<?php echo slug($form['form_name']); ?>"><?php
            foreach($form['sections'] as $section){
                ?><h2><?php echo $section['label']; ?></h2><?php
                foreach($section['fields'] as $field){
                    ?>
                        <label for="<?php echo slug($field['label']); ?>" class="<?php echo slug($field['label']); ?>">
                            <?php if($field['type']=='text'): ?>
                                <?php echo $field['label']; ?>: <input type="text" name="<?php echo slug($field['label']); ?>" id="<?php echo slug($field['label']); ?>">
                            <?php endif; ?>
                        </label>
                    <?php
                }
            }
        ?><input type="submit" value="Save"><?php
        ?></form>
        <script src="libs/validate.min.js"></script>
        <script>
            var form_validator = new FormValidator('<?php echo slug($form['form_name']); ?>', [
                <?php foreach($form['sections'] as $section): foreach($section['fields'] as $field): ?>
                    {
                        name: '<?php echo slug($field['label']); ?>',
                        rules: '<?php echo $field['rules']; ?>',
                        display: '<?php echo $field['label']; ?>'
                    },
                <?php endforeach; endforeach; ?>
            ], function(errors, event) {
                if (errors.length > 0) {
                    for(i=0;i<=errors.length;i++){
                        document.getElementById('messages').innerHTML += '<li>'+errors[i].message+'</li>'
                    }
                }
            });
        </script>
        <?php
    }
    ?>

matches[] doesn't work in fields like "jform[pass1]"

Joomla 1.7 for example, uses form field names as an array like jform[pass1]. Matching does not work in these.

Example code below (removed extra code for clarity purposes)

var validator = new FormValidator('member-registration', [
  { name: 'jform[email1]', display: 'email', rules: 'required|valid_email' },
  { name: 'jform[email2]', display: 'repeat email', rules: 'required|matches[jform[email1]]' }
], function(errors, events) {
  if (errors.length > 0) {
    // ...
  }
});
<form>
<input type="text" name="jform[email1]"  />
<input type="text" name="jform[email2]"  />
<input type="submit" />
</form>

Tried escaping 'squared parenthesis' like this but doesn't work (maybe this can be the way to go when field names have parenthesis):

matches[jform\[email1\]]

email regex

The email regex will allow a@b as a valid email. Should require a top level domain (.com, .net, etc).

Dynamic Input field and Validate.js

Hello Rick

if the input fields are already present validate.js works smoothly.
But if I am loading several input fields in a dynamic manner, how can i attach the new fields to the existing validate form variable for validation.

Thankfully
Karthik M

how to validate all field before JSF ajax call

my form fields are not getting validate for ajax call :

code on button click in my jsf form is like this :
<h:commandButton id="submit" type="submit" value="Add Row">
<f:ajax event="click" listener="#{billB.addItem}" execute="createBillForm" render=":createBillForm:wrapper" />
/h:commandButton

and the validation method is same as given on the site.

Please advice.

valid_email and alphanumeric

I can't get to see the error message for valid_email, not even on the demo live site.. only fires the required fields!

name: 'email',
rules: 'valid_email'

Rules field name

If field name has '[' ']' characters validations rules with parameters like "matches" does not work.

validate checkboxes

can you add support for checkboxes i changed the code: "

required: function(a) {
var b = a.value;
return (a.type === 'checkbox') ? ((a.type === 'checkbox') || (a.type === 'radio')) ? !0 === a.checked:"" : null !== b && "" !== b;

    }

"

using validate.js with google apps script

I love validate.js, but I am having hard time to get it to work in Google App Script web app.
It seems that forms build using HtmlService don't submit in the way how regular web form does.
How do I trigger the validation manually?
thanks in advance,
J

Validation fires several times

Hi,

I have a meteor app and I have the following validator: http://slexy.org/view/s2j75Huw31
The validator checks teacher registration form.
Validation passes, but the callback function gets called 2 times.
In both times - form_errors = []
I would expect the callback to be called only once.

Regards, Alex A.

Multiple validations on a single form control

I have a required phone number field, and I want to make sure to validate presence as well. So required and numeric is needed.

When I use just numeric, I don't get an error for lack of presence.

a regex validation

if you add a function that validate a gerex validation

i'm sorry for my english

Events after validation

I'm a javascript newbie, so please excuse my basic question here. I've implemented the validation script so that it correctly validates a few form fields. My question is: How do you tell the script to continue with the POST parameter of submitting the form, after successfully validating the fields?

Also, I think your instructions could benefit from having notation on including the *onSubmit="return FormValidator()" * code in the form tag.

Thanks very much in advance.

Error in the documentation

Hi,

you have an error in the documentation, in the callback function:

function(errors, event) {
    if (errors.length > 0) {
        // Show the errors

}

errors is an object and not an array, you cannot use errors.length, it returns always 'undefined'

I solved in this way:

function(errors, event) {
var count = 0;
    for (var x in errors) {
        count++;
    }
    if (count > 0) {
        // Show the errors
    }
}

"numeric" test regex appears incorrect

The test for the rule "numeric" uses the decimalRegex and not the numericRegex. While the decimalRegex seems to be more appropriate in this case, it's inconsistent with the other rules and perhaps we should:

  1. redefine numericRegex to allow decimals, and use this in the "numeric" rule rather than decimalRegex
  2. update the other rules that actually do use numericRegex to use another less confusingly-named rule for their purpose

Grouped inputs ([]) for PHP Arrays not being validated.

I have a form with some grouped input fields, which have a set of square brackets at the end of their names like so:

<input name="query_519535_2_0_0[]" id="query_519535_2_0_0_1" value="1" type="radio">
<input name="query_519535_2_0_0[]" id="query_519535_2_0_0_2" value="2" type="radio">
<input name="query_519535_2_0_0[]" id="query_519535_2_0_0_3" value="3" type="radio">

When I try to validate these groups of inputs like so:

var validationRules = [
        {name: 'query_519535_2_0_0[]', rules: 'required'}
    ];

hoping to validate whether any of the radio buttons have been selected, but nothing happens on submit. I have other inputs with no brackets in their names that are being validated as expected.

I tried removing the brackets from the JS but this resulted in the radio groups evaluating to false no matter what.

Muliple forms in the same page

Is it possible to have more than 1 form in the same page?
Because I'm having a problem to show the error message. When I had 1 form I had the following error_box:

and it worked fine. Now with 2 forms I changed the value of the classes for error_box1(form1) and error_box2(form2) and the div that contains the error message doesnt show anymore. I changed the value in my css file and in the javascript code too.

Where more do I have to change??

Thanks

JQuery

Is JQuery required for this script to work properly?

How to add custom rule to check if username exists

Hello thanks for the great tool

this is my working code :

new FormValidator('register_form', [{
name: 'firstname',
display: 'First name',
rules: 'required|min_length[3]|max_length[20]'
},{
name: 'lastname',
display: 'Last name',
rules: 'required|min_length[3]|max_length[20]'
},{
name: 'username',
display: 'Username',
rules: 'required|min_length[3]|max_length[20]|callback_check_user'
},], function(errors, event) {
var SELECTOR_ERRORS = $('.error_box');

if (errors.length > 0) {
    SELECTOR_ERRORS.empty();
    for (var i = 0, errorLength = errors.length; i < errorLength; i++) {
        SELECTOR_ERRORS.append(errors[i].message + '<br />');
    }
    SELECTOR_ERRORS.fadeIn(200);
}

});

i want to add a custom validation rule but i dont know where to put this code

validator.registerCallback('check_user', function(value) {
if (userisUnique(value)) {
return true;
}

return false;

})
.setMessage('check_user', 'That username is already taken. Please choose another.');

can you explain ? i know how to check if username exists , thanks

have the callback utilize a return value

it would be about 1000 times cooler if the callback returned a boolean which was used to indicate whether or not the form submit should take place.

Instead of

if (typeof this.callback === 'function') {
this.callback(this.errors, event);
}
if (this.errors.length > 0) {

do something like

var return_value = true;
if (typeof this.callback === 'function') {
return_value = this.callback(this.errors, event);
}
if (this.errors.length > 0 || return_value === false) {

that would really help when you do various ajax-y type of validation and form submits

provide access to invalid form elements

As suggested here:

If you passed through the element here (e.g. simply via field.element),
that would open up more options for presenting errors to the user - e.g.
displaying errors inline, close to the respective field element. (Perhaps
_validateField could trigger a simple event/callback for this?)

i have 8 upload section my page.........how can i validate them all

var validator = $("#aspnetForm").validate({
rules: {
file: {
required: true
}
},
messages: {
file: "Upload-Thumbnail1"
}
});
<asp:Label ID="lblThumbnail1" class="lbl" runat="server" Text="First Thumbnail Heading">/asp:Label
<asp:TextBox ID="txbThumbnail1" class="txtbox" runat="server" MaxLength="50">/asp:TextBox
<asp:RequiredFieldValidator ID="RFVThumbnail1" runat="server" ControlToValidate="txbThumbnail1"
SetFocusOnError="true" ErrorMessage="Please Enter Thumbnail Heading1.">/asp:RequiredFieldValidator




Please enable JavaScript to use file uploader.





<asp:Label ID="lblThumbnail2" runat="server" Text="Second Thumbnail Heading" class="lbl">/asp:Label
<asp:TextBox ID="txbThumbnail2" class="txtbox" runat="server" MaxLength="50">/asp:TextBox
<asp:RequiredFieldValidator ID="RFVThumbnail2" runat="server" ControlToValidate="txbThumbnail2"
SetFocusOnError="true" ErrorMessage="Please Enter Thumbnail Heading2.">/asp:RequiredFieldValidator



Please enable JavaScript to use file uploader.




<script type="text/javascript"> function createUploader() { var uploader = new qq.FileUploader({ element: document.getElementById('Upload-Thumbnail1'), action: 'FileUploadNewPage.ashx?id=Thumbnail1', debug: true }); var uploader = new qq.FileUploader({ element: document.getElementById('Upload-Thumbnail2'), action: 'FileUploadNewPage.ashx?id=Thumbnail2', debug: true }); var uploader = new qq.FileUploader({ element: document.getElementById('Upload-Thumbnail3'), action: 'FileUploadNewPage.ashx?id=Thumbnail3', debug: true }); } ``` // in your app create uploader as soon as the DOM is ready // don't wait for the window to load window.onload = createUploader; </script>

the above code only validates my 1st upload................but i want to validate my all upload  block...........so user should upload atleast 1 image
plz do help me out from dis problem thnx

Validate.js preventing form from submitting

I'm using a php form template with a clunky validation js that submits. After I replaced it with validate.js, I can't submit an empty form or completed form. Error message isn't displayed either. I've followed your instructions for syntax and including it. Loaded validate.min.js at bottom.

Could you see what's wrong my code below?

Many thanks.

<!DOCTYPE html>   
<!--[if lt IE 7 ]> <html lang="en" class="no-js ie6"> <![endif]-->
<!--[if IE 7 ]>    <html lang="en" class="no-js ie7"> <![endif]-->
<!--[if IE 8 ]>    <html lang="en" class="no-js ie8"> <![endif]-->
<!--[if IE 9 ]>    <html lang="en" class="no-js ie9"> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--><html lang="en" class="no-js"> <!--<![endif]-->
<head>
<title>Customization Form</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<link href="css/jquery-ui-1.10.2.custom.min.css" rel="stylesheet" type="text/css">
  <link href="css/style.css" rel="stylesheet" type="text/css">
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
  <script type="text/javascript" src="js/modernizr.custom.78028.js"></script>
</head>

<body>

<div id="mainForm">

  <h1>Customize Your Stamps</h1>
  <h2 class="bottom-small">Fill out the form below to customize your stamp order</h2>

<div class="error-box"></div>


<!-- begin form -->
    <form method=post enctype=multipart/form-data action=processor.php name="customization-form">

    <div class=mainForm id="mainForm_1">

          <ul class="top-form cf">
          <li class="mainForm" id="fieldBox_24">                    
                <label class="formFieldQuestion">Request Date</label>
                 <p>
                     <input type=text name="date" id="datepicker" size='10' value="">
                 </p>
           </li>

            <li class="" id="fieldBox_1">
                <label class="formFieldQuestion">First and Last Name</label>
                <input class=mainForm type=text name="full-name" id=field_1 size='45' value=''></li>

           <li class="" id="fieldBox_9">
                <label class="formFieldQuestion">Contact Name</label>
                <input class=mainForm type=text name="contact-name" id=field_9 size='20' value=''></li>


            <li class="" id="fieldBox_2">
                <label class="formFieldQuestion">Company</label>
                <input class=mainForm type=text name="company" id=field_2 size='40' value='Company Name'></li>

            <li class="" id="fieldBox_3">
                <label class="formFieldQuestion">E-mail Address</label>
                <input class=email type=email name="email" id=field_3 size='40' value=""></li>

            <li class="" id="fieldBox_4">
                <label class="formFieldQuestion">Order Number<a class=info href=#><img src=images/tip_small.png border=0><span class=infobox>Type your order number here.  You can find it in your order confirmation or by logging in to your account.</span></a></label>
                <input class=mainForm type=text name="order-number" id=field_4 size='30' value=''></li>

            <div class="grid-row cf">
                <li class="left right-small" id="fieldBox_5">
                    <label class="formFieldQuestion">Phone Number</label>
                    <input class=phone type=phone name="phone" id=field_5 size='20' value=""></li>

                <li class="left" id="fieldBox_6">
                    <label class="formFieldQuestion">Fax Number</label>
                    <input class=mainForm type=text name="fax" id=field_6 size='20' value=''></li>
           </div><!-- grid-row -->

            <div class="grid-row">
              <li class="left right-small" id="fieldBox_8">
                <label class="formFieldQuestion">City</label>
                <input class=mainForm type=text name="city" id=field_8 size='25' value=''></li>

            <li class="left bottom-medium" id="fieldBox_7">
                <label class="formFieldQuestion">State</label>
                <select class=mainForm name="state" id=field_7>
                <option value=''> </option><option value="Alabama">Alabama</option><option value="Alaska">Alaska</option><option value="Arizona">Arizona</option><option value="Arkansas">Arkansas</option><option value="California">California</option><option value="Colorado">Colorado</option><option value="Connecticut">Connecticut</option><option value="Delaware">Delaware</option><option value="Florida">Florida</option><option value="Georgia">Georgia</option><option value="Hawaii">Hawaii</option><option value="Idaho">Idaho</option><option value="Illinois">Illinois</option><option value="Indiana">Indiana</option><option value="Iowa">Iowa</option><option value="Kansas">Kansas</option><option value="Kentucky">Kentucky</option><option value="Louisiana">Louisiana</option><option value="Maine">Maine</option><option value="Maryland">Maryland</option><option value="Massachusetts">Massachusetts</option><option value="Michigan">Michigan</option><option value="Minnesota">Minnesota</option><option value="Mississippi">Mississippi</option><option value="Missouri">Missouri</option><option value="Montana">Montana</option><option value="Nebraska">Nebraska</option><option value="Nevada">Nevada</option><option value="New Hampshire">New Hampshire</option><option value="New Jersey">New Jersey</option><option value="New Mexico">New Mexico</option><option value="New York">New York</option><option value="North Carolina">North Carolina</option><option value="North Dakota">North Dakota</option><option value="Ohio">Ohio</option><option value="Oklahoma">Oklahoma</option><option value="Oregon">Oregon</option><option value="Pennsylvania">Pennsylvania</option><option value="Rhode Island">Rhode Island</option><option value="South Carolina">South Carolina</option><option value="South Dakota">South Dakota</option><option value="Tennessee">Tennessee</option><option value="Texas">Texas</option><option value="Utah">Utah</option><option value="Vermont">Vermont</option><option value="Virginia">Virginia</option><option value="Washington">Washington</option><option value="West Virginia">West Virginia</option><option value="Wisconsin">Wisconsin</option><option value="Wyoming">Wyoming</option>
                </SELECT>
                </li>
              </div><!-- grid-row -->
            </ul>


            <ul class="grid-row cf">
            <li class="" id="fieldBox_10">
                <label class="formFieldQuestion">Stock Number</label>
                <input class=mainForm type=text name="stock-number" id=field_10 size='15' value=''></li>

            <li class=" right-medium" id="fieldBox_22">
                    <label class="formFieldQuestion">Font<a class=info href=#><img src=images/tip_small.png border=0><span class=infobox>Arial is default. Type any font here instead of Arial.</span></a></label>
                    <input class=mainForm type=text name="font" id=field_20 size='20' placeholder="Type font name"></li>


            <li class="" id="fieldBox_12">
                <label class="formFieldQuestion">Font Size<a class=info href=#><img src=images/tip_small.png border=0><span class=infobox>Select font size of stamp</span></a></label>
                <select class=mainForm name="font-size" id=field_12>
                <option value=''></option><option value="8">8</option><option value="9">9</option><option value="10">10</option><option value="11">11</option><option value="12">12</option><option value="14">14</option><option value="16">16</option><option value="18">18</option><option value="20">20</option><option value="22">22</option><option value="24">24</option><option value="26">26</option><option value="28">28</option><option value="36">36</option><option value="48">48</option><option value="72">72</option>
                </select></li>

            <li class="" id="fieldBox_11">
                <label class="formFieldQuestion">Ink Color<a class=info href=#><img src=images/tip_small.png border=0><span class=infobox>Select color of stamp</span></a></label>
                <select class=mainForm name="ink-color" id=field_11>
                <option value=''></option><option value="Black">Black</option><option value="Blue">Blue</option><option value="Red">Red</option><option value="Green">Green</option><option value="Purple">Purple</option>
                </select></li>  

            <li class="" id="fieldBox_13">
                <label class="formFieldQuestion">Quantity</label>
                <input class=mainForm type=text name="quantity" id=field_13 size='8' value=''></li>
            </ul>   <!-- grid-row -->



            <ul class="grid-row cf">
            <li class="" id="fieldBox_14">
                <label class="formFieldQuestion">Stock Number</label>
                <input class=mainForm type=text name="stock-number2" id=field_14 size='15' value=''>
            </li>
           <li class=" right-medium" id="fieldBox_23">
                <label class="formFieldQuestion">Font<a class=info href=#><img src=images/tip_small.png border=0><span class=infobox>Arial is default. Type any font here instead of Arial.</span></a></label>
                <input class=mainForm type=text name="font2" id=field_20 size='20' placeholder="Type font name"></li>


            <li class="" id="fieldBox_16">
                <label class="formFieldQuestion">Font Size<a class=info href=#><img src=images/tip_small.png border=0><span class=infobox>Select font size of stamp</span></a></label>
                <select class=mainForm name="font-size2" id=field_16>
                <option value=''></option><option value="8">8</option><option value="9">9</option><option value="10">10</option><option value="11">11</option><option value="12">12</option><option value="14">14</option><option value="16">16</option><option value="18">18</option><option value="20">20</option><option value="22">22</option><option value="24">24</option><option value="26">26</option><option value="28">28</option><option value="36">36</option><option value="48">48</option><option value="72">72</option>
                </select>
                </li>

           <li class="" id="fieldBox_15">
                <label class="formFieldQuestion">Ink Color<a class=info href=#><img src=images/tip_small.png border=0><span class=infobox>Select color of stamp</span></a></label>
                <select class=mainForm name="ink-color2" id=field_15>
                <option value=''></option>
                <option value="Black">Black</option>
                <option value="Blue">Blue</option>
                <option value="Red">Red</option>
                <option value="Purple">Purple</option>
                <option value="Green">Green</option>
                </select>
                </li>

            <li class="" id="fieldBox_17">
                <label class="formFieldQuestion">Quantity</label>
                <input class=mainForm type=text name="quantity2" id=field_17 size='8' value=''></li>
            </ul><!-- grid-row -->

            <ul class="grid-row cf ">
            <li class="" id="fieldBox_18">
                <label class="formFieldQuestion">Stock Number</label>
                <input class=mainForm type=text name="stock-number3" id=field_18 size='15' value=''></li>

            <li class=" right-medium" id="fieldBox_20">
                <label class="formFieldQuestion">Font<a class=info href=#><img src=images/tip_small.png border=0><span class=infobox>Arial is default. Type any font here instead of Arial.</span></a></label>
                <input class=mainForm type=text name="font3" id="font" size='20' placeholder="Type font name"></li>

            <li class="" id="fieldBox_21">
                <label class="formFieldQuestion">Font Size<a class=info href=#><img src=images/tip_small.png border=0><span class=infobox>Select font size of stamp</span></a></label>
                <select class=mainForm name="font-size3" id=field_21>
                <option value=''></option><option value="8">8</option><option value="9">9</option><option value="10">10</option><option value="11">11</option><option value="12">12</option><option value="14">14</option><option value="16">16</option><option value="18">18</option><option value="20">20</option><option value="22">22</option><option value="24">24</option><option value="26">26</option><option value="28">28</option><option value="36">36</option><option value="48">48</option><option value="72">72</option>
                </select>
                </li>

           <li class="" id="fieldBox_19">
                <label class="formFieldQuestion">Ink Color<a class=info href=#><img src=images/tip_small.png border=0><span class=infobox>Select color of stamp</span></a></label>
                <select class=mainForm name="ink-color3" id=field_19>
                <option value=''></option><option value="Black">Black</option><option value="Blue">Blue</option><option value="Red">Red</option><option value="Purple">Purple</option><option value="Green">Green</option>
                </select>
                </li>

            <li class="" id="fieldBox_25">
                    <label class="formFieldQuestion">Quantity</label>
                    <input class=mainForm type=text name="quantity3" id=field_17 size='8' value=''></li>
            </ul><!-- grid-row -->

        <ul class="grid-row cf ">
            <li class="mainForm" id="fieldBox_26">
                <label class="formFieldQuestion">Text Alignment</label>
                <span>
                 <input class=mainForm type=radio name="text-alignment" id=field_26_option_1 value="left" />
                 <label class=formFieldOption for="field_26_option_1">stamp text is left aligned</label>
                 <input class=mainForm type=radio name="text-alignment" id=field_26_option_2 value="right" />
                 <label class=formFieldOption for="field_26_option_2">stamp text is right aligned</label>
                 <input class=mainForm type=radio name="text-alignment" id=field_26_option_3 value="center" />
                 <label class=formFieldOption for="field_26_option_3">stamp text is center aligned</label>
                </span>
            </li>
        </ul><!-- grid-row -->

            <ul class="grid-row cf ">
            <li class="mainForm" id="fieldBox_27">
                <label class="formFieldQuestion">Stamp Details&nbsp;*</label>
                <textarea class=mainForm name="stamp-details" id=field_27 rows="8" cols="60" placeholder="Type what you would like on your stamp here.">

              </textarea>
            </li>
        </ul> <!-- grid-row -->



                 <div class="top-small ">
                <input id="saveForm" class="button" type="submit" value="Send information" />
            </div>

        </form>
        <!-- end of form -->
    </div>

  <script type="text/javascript" src="js/calendar-new.js"></script>      
   <script type="text/javascript" src="js/validate.min.js"></script>


   <script type="text/javascript">

     new FormValidator("customization-form", [{
        name: "date",
        display: "date",
        rules: "required"
     }, {
        name: "full-name",
        display: "first and last name",
        rules: "required|alpha"
     }, { 
        name: "contact-name",
        display: "contact name",
        rules: "required|alpha"
     }, {
        name: "company", 
        display: "contact name",
        rules: "required"
     }, {
        name: "email",
        display: "email address",
        rules: "required|valid_email"
     }, {
        name: "order-number",
        display: "order number",
        rules: "required|greater_than[1000]|numeric"
     }, {
        name: "phone",
        display: "phone number",
        rules: "required"
     }, {
        name: "fax",
        display: "fax number",
        rules: "required"
     }, {
            name: "city",
            display: "city",
        rules: "required"
     }, {
           name: "state",
           display: "state",
        rules: "required"
        }, {
            name: "stock-number", 
            display: "stock number",
        rules: "required|numeric"
    }, {
           name: "font",
           display: "choice of font",
        rules: "required"
        }, {
            name: "font-size",
            display: "font size",
        rules: "required" 
       }, {
            name: "ink-color",
            display: "ink color",
        rules: "required|alpha"
     }, {
            name: "quantity",
            display: "quantity",
        rules: "required|greater_than[1]|numeric"
       }, {             
          name: "text-alignment",
          display: "text alignment",
        rules: "required"
       }, {
            name: "stamp-details",
            display: "stamp details",
        rules: "required"         
     }], function(errors, evt) {
         var SELECTOR_ERRORS = $('.error_box'),
             SELECTOR_SUCCESS = $('.success_box');

         if (errors.length > 0) {
             SELECTOR_ERRORS.empty();

             for (var i = 0, errorLength = errors.length; i < errorLength; i++) {
                 SELECTOR_ERRORS.append(errors[i].message + '<br />');
             }

             SELECTOR_SUCCESS.css({ display: 'none' });
             SELECTOR_ERRORS.fadeIn(200);
         } else {
             SELECTOR_ERRORS.css({ display: 'none' });
             SELECTOR_SUCCESS.fadeIn(200);
         }

     });
   </script>

</body>
</html>

How can i change the submit event?

I want to call an ajax function, after the plugin validates my forms ... I do not understand where I can put the code, because if I call a function in ajax error checking (if validation errors are 0) the script generates a loop and launches the ajax function as many times as those that I pressed the button send.
I copied the function written on the demo site, with even the evt.preventDefault.
Thank you very much

callback method not working

I have this form validator which has a custom callback but it doesn't work:

var customvalidation = new FormValidator('new_form', [{
    name: 'custom_field',
    display: 'Form Field',    
    rules: 'callback_check_field'
}], function(errors, event) {
    var SELECTOR_ERRORS = $('.error_box'),
        SELECTOR_SUCCESS = $('.success_box');

    if (errors.length > 0) {
        SELECTOR_ERRORS.empty();
        SELECTOR_ERRORS.append(errors.join('<br />'));

        SELECTOR_SUCCESS.css({ display: 'none' });
        SELECTOR_ERRORS.fadeIn(200);
    } else {
        SELECTOR_ERRORS.css({ display: 'none' });
        SELECTOR_SUCCESS.fadeIn(200);
    }

    if (event && event.preventDefault) {
        event.preventDefault();
    } else if (event) {
        event.returnValue = false;
    }
});

callback function

customvalidation.registerCallback('check_field', function(value) {
    alert("test alert");
    return false;
});

Use data- attributes instead of/in addition to initializer hash

Seems wrong to keep this data separate from the fields themselves, e..g.:

Additionally, I'm curious why you aren't using HTML5 attributes for some of the values. Specifically for required but also where available for type of input (type="url", type="number", min/max length, pattern).

Form Fires on Error

Hey Rick,

Great library and precisely what I was looking for. I'm having an issue where the form is being submitted even though there is an error firing. Essentially, I leave the form blank, I click submit, validation occurs and adds an error message but it continues to post anyways. Any idea what I'm doing wrong?

<form action="http://ipaddress/url/addIssue" name="issue-form">
  // Form Logic
  <button class="btn btn-large btn-block btn-success">Add Issue</button>
</form>
<script type="text/javascript" src="assets/js/validate-rules.js"></script>
</body>

validate-rules.js

var validator = new FormValidator('issue-form', [{
  name: 'title',
  rules: 'required'
}], function(errors, event) {
  if(errors.length > 0) {
    var selector_errors = $('.error-box');
    if (errors.length > 0) {
      selector_errors.empty();
    for (var i = 0, errorLength = errors.length; i < errorLength; i++) {
      selector_errors.append(errors[i].message + '<br />');
    }
      selector_errors.fadeIn(200);
    }
    if(evt && evt.preventDefault) {
      evt.preventDefault();
    } else if (event) {
      event.returnValue = false;
    } 
  } else {
    copy_values();
  }
});

Any idea what I'm doing wrong?

Binds, Fails Test, But Doesn't Block Submission?

Thanks for this code. It's well documented and nicely commented, so I was able to easily get it installed and then follow code execution in the browser's debugger.

But that doen't mean I can figure out why it doesn't block the form submission when a required field is left blank.

I'm using it within a Meteor project, which runs a good bit differently than a traditional MAMP stack does, as I'm slowly learning (I'm still pretty new to Meteor). So my html partial looks like this (ContactForm.html):

<template name="ContactForm">
<form class="contactform" id="contactForm" name="ContactForm">
    <fieldset>
        <div class="contactform-name contactform-field">
            <label class="contactform-label" for="contactform-name">Name:
                <br>
            </label>
            <input class="contactform-input" type="text" id="contactform-name" name="name" />
        </div>
        <input class="contactform-button" type="submit" name="submit" value="Send" />
    </fieldset>
</form>

And I bind the code in like this (ContactForm.js):

Template.ContactForm.rendered = function () {
var validator = new FormValidator('ContactForm',
    [{
    name: 'name',
    display: 'required',
    rules: 'required'
    }]
);
}

When I step through the executing code in the debugger, I see it pick up the field, check it, find that it's blank and flags the error, calls evt.preventDefault(); and returns true. But the form is submitted anyway!

What have I misconfigured or misunderstood?

Additional registerCallback doesn't fire

Hi Rick,

Thanks for your quick help on the previous issue. I noticed when I try to register a second call back, it never fires.

var validator = new FormValidator('issue-form', [{
    name: 'status',
    rules: 'required|callback_resolved_date_requirements'
}, {
    name: 'reportedBy',
    rules:'required|callback_resolved_reportedBy' // Doesn't fire callback. Only fits required rule.
}], function(errors, evt) {
    if(errors.length > 0) {
      // Error Handling, works fine.
        }
});

validator.registerCallback('resolved_date_requirements', function(status) {
    // Business Logic. This callback works fine.
}).setMessage('resolved_date_requirements', 'In order to resolve an issue, you must enter a detected, start, fix and resolution time.');

validator.registerCallback('resolved_reportedBy', function(reported) {
    console.log("This will never fire.");
        // Business logic.
}).setMessage('resolved_reportedBy', 'In order to resolve an issue, you must select an option in Reported By.');
// Never sends this message. It displays "The reportedBy field is required.", instead.

Any idea what I might be doing wrong?

Validating on group checkbox

I have a survey, lot of inputs need to be validated, validate.js works well on my most inputs and textareas.
But, I found it did not works multi checkboxs with same name, like this

<input type="checkbox" name="cb" value="A">
<input type="checkbox" name="cb" value="B">
<input type="checkbox" name="cb" value="C">

After checking the source and some testing, I added something on function attributeValue, let it works like the radio.

change

if ((element.length > 0) && (element[0].type === 'radio')) {

to

if ((element.length > 0) && ((element[0].type === 'radio') || (element[0].type === 'checkbox')) ) {

done.

Even though I can not ensure if this changing will do something bad else, but so far, it works well for me. 👯

And thanks! :D

if there is user-defined onsubmit?

If user assigned onsubmit function, validate.js override it.

It can be avoided like that below.

    /*
     * Attach an event callback for the form submission
     */

    var _onsubmit = this.form.onsubmit;
    this.form.onsubmit = (function(that) {
        return function(event) {
            try {
                return that._validateForm(event) && (undefined === _onsubmit || _onsubmit());
            } catch(e) {}
        }
    })(this);

Nothing happens when I click next

I have a form created with the validation at the end of the page. When I click next, nothing happens in Chrome or Firefox. I am not sure how to debug javascript. Do you know what could be causing this? I'm running locally on MAMP in a php file.

Problem to validate not required and custom rule

Hi Rick!
I'm using your excellent plugin but i run to some small problem:
In my form i have one field that not required (user may choose to leave it empty)
But once some input specified - it must be numeric and correspond to some pattern.
When i put only numeric or only my custom pattern rule in the plugin options - the plugin carry about empty field as valid (as needed).
But if i specify both: numeric and my custom rule - the empty field not consider as valid by plugin anymore(which is problematic for my case -i need user to be able to send empty field).
here is my code in jsbin that reproducing the problem:
http://jsbin.com/opazur/1
May be i'm doing something wrong, so i will glad if you(or somebody else) explain me where my mistake.
Thanks forward

submit function in another function

I am trying to use stripe to process a deposit after the top part of a form is validated. It is calling the function, but is submitting right away. Is it possible to pass the onsubmit event through the functions? I'm a noob at javascript. It doesn't seem to be disabling the form.

new FormValidator('deposit-form', [{
name: 'email',
rules: 'required|valid_email'
}], function(errors, evt) {

var SELECTOR_ERRORS = $('.error_box');

if (errors.length > 0) {
    SELECTOR_ERRORS.empty();

    SELECTOR_ERRORS.append(errors[0].message);
    SELECTOR_ERRORS.fadeIn(200);
    return false;
} else {
    SELECTOR_ERRORS.css({ display: 'none' });
    submitDeposit(evt);
}

});

function submitDeposit(evt) {
// Stripe Error checking
Stripe.setPublishableKey('');

var $deposit_form = $('#deposit-form');
var stripeResponseHandler = function(status, response) {
if (response.error) {
// Show the errors on the form
$deposit_form.find('.error_box').text(response.error.message).css( "display", "inherit" );
} else {
// token contains id, last4, and card type
var token = response.id;
// Insert the token into the form so it gets submitted to the server
$deposit_form.append($('').val(token));
// and re-submit
$deposit_form.get(0).submit();
}
};

$('#deposit-form').submit(function(evt) {

Stripe.createToken($deposit_form, stripeResponseHandler);

// Prevent the form from submitting with the default action
//return false;
//e.preventDefault();
if (evt && evt.preventDefault) {
  evt.preventDefault();
} else if (event) {
  // IE uses the global event variable
  event.returnValue = false;
}

});
}

Hidden form elements

Is there a rule to not validate hidden form elements but validate when they are visible? At the moment I've just created my own validation rule but it would be cool if there was already a rule for it.

Cannot Get form to submit, just validate

I am using the same code you have posted on your demo and I cannot get the form to submit if the user passes validation: Code Below:

                var validator = new FormValidator('newsletter_form', [{
                name: 'c_firstname',
                rules: 'required',
                display: 'First Name'
                }, {
                name: 'c_lastname',
                rules: 'required',
                display: 'Last Name'
                }, {
                name: 'c_emailaddress',
                rules: 'required|valid_email',
                display: 'Email Address'
                 }], function(errors, event) {
                var SELECTOR_ERRORS = $('.error_box'),
                SELECTOR_SUCCESS = $('.success_box');

                if (errors.length > 0) {
                    SELECTOR_ERRORS.empty();

                    for (var i = 0, errorLength = errors.length; i < errorLength; i++) {
                        SELECTOR_ERRORS.append(errors[i].message + '<br />');
                    }

                    SELECTOR_SUCCESS.css({ display: 'none' });
                    SELECTOR_ERRORS.fadeIn(200);

                } else {
                    SELECTOR_ERRORS.css({ display: 'none' });
                    SELECTOR_SUCCESS.fadeIn(200).$("#webform-client-form-372").submit();

                }

                if (event && event.preventDefault) {
                    event.preventDefault();
                } else if (event) {
                    event.returnValue = false;
                }
        });

How would I get this to submit the form if user passes validation?

Custom function is not called

I see an issue about that on #7 page. I should hava at least 'require' rule to run my custom function. But i only want to run my own custom function. Is there any effective solution for this?

var validator = new FormValidator('order_form', [{
    name: 'card_name',
    display: 'Card Name',
    rules: 'callback_card_control'
}]);

validator.registerCallback('card_control', function(value) {
    // not working
});

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.