【网页-JQuery插件】parsley.js使用

http://blog.163.com/yu_sky/blog/static/209817073201572393752391/


1、引入parsley.js

js中调用
<script src="jquery.js"> </script> <script src="parsley.min.js"> </script> <form id="form"> ... </form> <script type="text/javascript"> $('#form').parsley(); </script>

parsley常用方法调用如下:
$( '#form' ).parsley();
$( '#form' ).parsley( 'validate' );
$( '#form' ).parsley( 'isValid' );
$( '#form' ).parsley( 'destroy' );
$( '#form' ).parsley( 'addItem', '#itemid' );
$( '#form' ).parsley( 'removeItem', '#itemid' );
$( '#field' ).parsley( 'validate' );
添加一个新的约束方法:
$( '#field' ).parsley( 'addConstraint', { minlength: 2 } );
更新一个约束:
$( '#field' ).parsley( 'updateConstraint', { minlength: 6 } );
删除一个约束:
$( '#field' ).parsley( 'removeConstraint', 'minlength' );
总结一下调用方法即使:
$( '#parsleyFormOrFieldId' ).parsley( 'functionName', parameter );

$('#form').parsley(options);
options为参数,可以自定义,还有如下用法:
$ API Return
$('#existingForm').parsley(options) #2.0 parsleyFormInstance
$('#existingInput').parsley(options) #2.0 parsleyFieldInstance
$('#notExistingDOMElement').parsley(options) #2.0 undefined
$('.multipleElements').parsley(options) #2.0 Array[Instances]
具体列子如下:

The multiple options can be specified using data attributes and javascript:

<input id="first" data-parsley-maxlength="42" value="hello"/>
<input id="second" value="world"/>
[...]
<script>
var instance = $('#first').parsley();
console.log(instance.isValid()); // maxlength is 42, so field is valid
$('#first').attr('data-parsley-maxlength', 4);
console.log(instance.isValid()); // No longer valid, as maxlength is 4
// You can access and override options in javascript too:
instance.options.maxlength++;
console.log(instance.isValid()); // Back to being valid, as maxlength is 5
// Alternatively, the options can be specified the first time a form/field is bound:
var otherInstance = $('#second').parsley({
  maxlength: 10
});
console.log(otherInstance.options); // Shows that maxlength will be 10 for this field
<form> <input/></form>[...]<script>Parsley.options.maxlength = 42;var formInstance = $('form').parsley();var field = $('input').parsley();console.log(field.options.maxlength); // Shows that maxlength is 42Parsley.options.maxlength = 30;console.log(field.options.maxlength); // Shows that maxlength is automagically 30formInstance.options.maxlength++;console.log(field.options.maxlength); // Shows that maxlength is automagically 31

example:

<input data-my-namespace-priority-enabled="false">
[...]
<script>
var instance = $('input').parsley({namespace: 'my-namespace-'});
if (false === instance.options.priorityEnabled)
  console.log("priorityEnabled was set to false");

3、自定义一个校验器

<input type="text" data-parsley-multipleof="3" /> [...] <script type="text/javascript"> window.Parsley .addValidator('multipleof', { requirementType: 'integer', validateNumber: function(value, requirement) { return 0 === value % requirement; }, messages: { en: 'This value should be a multiple of %s', fr: 'Cette valeur doit être un multiple de %s' } ); </script>
参数、错误信息说明如下:

The following sections go over the details on how to define a custom validator

Validating function

There are many ways a validator can specify how to validate data:

Name Description
validateString Is passed the input's value as a string.
validateNumber Use this instead of validateString when only numeric values are acceptable. Parsley will parse the input's value and pass the number, or reject the value if it's not an acceptable number
validateMultiple Is passed an array of values, in the case of checkboxes.

Your custom validator must specify at least one of these. If it can validate both single inputs and multiple (i.e. checkboxes), then you can specify validateMultiple and one of the other two.

Validating functions should return either true if the value is valid, or false otherwise. It can instead return a promise that will be resolved if the value is valid, or be rejected otherwise.

Requirement parameters

You can specify what kind of requirement parameter your custom validator is expecting:

requirementKind Description
string The most generic kind; requirement passed as is, with no checking.
integer For integers only (e.g. used by minlength)
number To be used when decimal numbers are acceptable
regexp Requirement can be either a full regexp string (e.g. /hel+o/i) or just a simple expression (e.g. hel+o)
boolean Any value other than "false" will be considered to true, including the empty string. This is so data-parsley-required and data-parsley-required=true be treated the same way.

You can also specify an array of these kinds. For example, if a validator has requirementKind: ['integer', 'integer'], then given the requirement string "[1, 2]" it will receive 1 and 2 as second and third arguments (the first one being the value(s) to validate).

For even cases where more complex parameters are needed, you can specify extra parameters; refer to the source and check how the remote validator uses that.

Error messages

You can specify error messages, in as many locales as desired, using the messages option.

This is equivalent to calling addMessage for each locale.


给表单或输入框 添加一个约束的另一个列子:

默认的如下:

Default is:

{
  // basic parsley-api overridable properties here..
  inputs: 'input, textarea, select'
  , excluded: 'input[type=hidden]'
  , trigger: false
  , animate: true
  , focus: 'first'
  , validationMinlength: 3
  , successClass: 'parsley-success'
  , errorClass: 'parsley-error'
  , validators: {}
  , showErrors: true
  , useHtml5Constraints: true
  , messages: {}

  //some quite advanced configuration here..
  , validateIfUnchanged: false
  , errors: {                     // specify where parsley error-success classes are set
    classHandler: function ( elem, isRadioOrCheckbox ) {}
  , container: function ( elem, isRadioOrCheckbox ) {}
  , errorsWrapper: '<ul></ul>'
  , errorElem: '<li></li>'
  }
  , listeners: {
      onFieldValidate: function ( elem, ParsleyField ) { return false; }
    , onFormValidate: function ( isFormValid, event, ParsleyForm ) {}
    , onFieldError: function ( elem, constraints, ParsleyField ) {}
    , onFieldSuccess: function ( elem, constraints, ParsleyField ) {}
  }
}

可通过此方法新增,具体方法如下:

官网给出的列子如下:

$( '#form' ).parsley( { validators: { multiple: function() { return { validate: function(val, multiple) { return val % multiple === 0; }, priority: 2 }; } } , messages: { multiple: "This value should be a multiple of %s" }} );<input type="text" parsley-multiple="3" />


但自己运行不通,改造如下:

<form id="form" name="form" data-parsley="validate">

    <input type="text" 

    id="parsley-multiple" 

    data-trigger="keyup" 

    data-multiple="3" 

    placeholder="multiple of 3" 

    class="parsley-validated parsley-error">

    

</form>


$('#parsley-multiple').parsley( {

                validators: {

                  multiple: function(val, multiple) {

                     console.log(val)

                     console.log(multiple)

                     return val % multiple === 0;

                    /**


                    return {

                      valid: function(val, multiple) {

                        //console.log(val)

                        //console.log(multiple)

                        return val % multiple === 0;

                      }//,

                     // priority: 2

                    }

                    */

                  }

                }

              , messages: {

                  multiple: "This value should be a multiple of %s"

                }

            } );

添加一个监听方法列子如下:

$( '#form' ).parsley( 'addListener', { onFieldValidate: function ( elem ) { // if field is not visible, do not apply Parsley validation! if ( !$( elem ).is( ':visible' ) ) { return true; } return false; }} );


3.1

自定义css如下:

$('#form').parsley({ successClass: 'my-class-name', errorClass: 'still-my-class-name' });

$('#form').parsley( { errors: { classHandler: function ( elem, isRadioOrCheckbox ) { return $( elem ).parent(); } }} );

errors: { container: function (element, isRadioOrCheckbox) { var $container = element.parent().find(".parsley-container"); if ($container.length === 0) { $container = $("<div class='parsley-container'></div>").insertBefore(element); } return $container; }}



4、ui for javascript

Name Method Description
Add error #2.0 window.ParsleyUI.addError(parsleyInstance, name, message); Manually add an error message.
Update error #2.0 window.ParsleyUI.updateError(parsleyInstance, name, message); Manually edit an error message.
Remove error #2.0 window.ParsleyUI.removeError(parsleyInstance, name); Manually remove an error message.
Get errors messages#2.0 window.ParsleyUI.getErrorsMessages(parsleyInstance); Returns an array of the field errors messages displayed once validated.

5、事件说明

$('#some-input').parsley().on('field:success', function() {
  // In here, `this` is the parlsey instance of `#some-input
});

Similarly to jQuery events, parsley events will bubble up. For example, if a field is about to be validated, the event'field:validate' will be triggerred first on the parsley field instance, then on the parsley form instance (if the field is bound in a form) and finally on the top level window.Parsley

window.Parsley.on('field:error', function() {
  // This global callback will be called for any field that fails validation.
  console.log('Validation failed for: ', this.$element);
});

.

事件列表如下:

Name Instance Fired by Description
form:init #2.1 ParsleyForm new Parsley() Triggered when a Form is bound for the first time.
form:validate #2.1 ParsleyForm .validate() Triggered when a form validation is triggered, beforeits validation.
form:success #2.1 ParsleyForm .validate() Triggered when a form validation is triggered, after its validation succeeds.
form:error #2.1 ParsleyForm .validate() Triggered when a form validation is triggered, after its validation fails.
form:validated #2.1 ParsleyForm .validate() Triggered when a form validation is triggered, after its validation finishes (with success or with errors).
form:submit #2.2 ParsleyForm submit() Triggered when after a form validation succeeds and before the form is actually submitted.
Prevent the default to interrupt submission.
field:init #2.1 ParsleyField new Parsley() Triggered when a Field is bound for the first time.
field:validate #2.1 ParsleyField .validate() Triggered when a field validation is triggered, before its validation.
field:success #2.1 ParsleyField .validate() Triggered when a field validation succeeds.
field:error #2.1 ParsleyField .validate() Triggered when a field validation fails.
field:validated #2.1 ParsleyField .validate() Triggered after a field is validated (with success or with errors).

6、parsley后台ajax校验

Options

Name API Description
Remote validator data-parsley-remote #2.0 Define the url that will be called to validate the entered content. e.g.data-parsley-remote="http://url.ext"
Reverse data-parsley-remote-reverse#2.0 By default, all 2xx ajax returs are considered valid, all others failure. Sometimes (when a call is needed to see if an email, a pseudo is available for example) a 404 API answer could be the right answer. Usingdata-parsley-remote-reverse="true" will consider 200 response is an error, and 404 one is correct.
Options data-parsley-remote-options#2.0 You could pass a json object to the $.ajax()method used by remote validator. eg:
data-parsley-remote-options='{ "type": "POST", "dataType": "jsonp", "data": { "token": "value" } }'
Warning: you must format your JSON string wrapping all the keys/values with " like above otherwise it won't be correctly parsed by$.parseJSON() used behind the scenes by remote validator (See jQuery doc)
Validator data-parsley-remote-validator#2.0

Use a specific remote validator. By default, there are 2 built-in remote validators: default and reverse. Default one is used by default and Reverse one used when data-parsley-remote-reverse is set to true. (this is an alias, you could usedata-parsley-remote-validator="reverse").

Inside the function, this keyword refers to theParsleyField instance attached to the form element. You have access to the plugin as well as the element if you need to perform other actions before returning the validation result.

To learn how to craft your custom remote validators, go here.

方法:
Method Description
Parsley.addAsyncValidator(name, fn) #2.0 Specify custom validator for Ajax results.

自定义的本地校验器

If you need some custom processing of Ajax responses, configure your custom remote as follows:

<input name="q" type="text" data-parsley-remote data-parsley-remote-validator='mycustom' value="foo" />
[...]
<script href="parsley.remote.js"></script>
<script href="parsley.js"></script>
<script type="text/javascript">
window.Parsley.addAsyncValidator('mycustom', function (xhr) {
    console.log(this.$element); // jQuery Object[ input[name="q"] ]

    return 404 === xhr.status;
  }, 'http://mycustomapiurl.ext');
</script>

Parsley Extras


猜你喜欢

转载自blog.csdn.net/cracklibby/article/details/80013002
今日推荐