Skip to content
Jony edited this page Sep 3, 2015 · 2 revisions

Include niceValidator

First of all, ensure that you had included jQuery (1.7+).
Then you can choose one of the following three ways to include plug-in:

way 1: Include directly (Global)

Just add a script, pass a parameter named "local", and the value is your local filename.

<script src="path/to/nice-validator/jquery.validator.js?local=en"></script>

way 2: Included by RequireJS (AMD)

You can only use the local setting file as entry.
eg. If you use English, and you will use local/en.js

requirejs.config({
    paths: {
        validator: 'path/to/nice-validator/local/en'
    }
});

way 3: Included by Sea.js (CMD)

You can only use the local setting file as entry.
eg. If you use Chinese, and you will use local/zh-CN.js

seajs.config({
    alias: {
        validator: 'path/to/nice-validator/local/zh-CN'
    }
});

Initialize Form Validation

You can use JS initialization or DOM bindings, even mixed two way.

way 1: DOM bindings

<form id="form1" action="register.php">
    <label>Email</label>
    <input type="email" name="email" data-rule="required;email">
    <label>Password</label>
    <input type="password" name="pwd" data-rule="required;length(6~16)">
</form>

way 2: JS initialization

<form id="form1" action="register.php">
    <label>Email</label>
	<input type="email" name="email">
    <label>Password</label>
	<input type="password" name="pwd">
</form>

Use the follow javascript:

$('#form1').validator({
    fields: {
        'email': 'required;email',
        'pwd': 'required;length(6~16)'
    }
});

way 3: DOM bindings with JS initialization

<form id="form1" action="register.php">
    <label>Email</label>
	<input type="email" name="email" data-rule="required;email">
    <label>Password</label>
	<input type="password" name="pwd" data-rule="required;length(6~16)">
</form>
$('#form1').validator();

Submit Form

  • If you initialization form validation by DOM bindings (like above example), this will be a native submit (page will reload after the submiting).
  • If you use valid parameter or valid.form event, form will not be automatically submited after the form is valid. you should submit the form by yourself. Use native submit or ajax submit ? Look at your needs. For example:
$('#form1').validator({
    fields: {
        'email': 'required;email',
        'pwd': 'required;length(6~16)'
    },
    valid: function(form) {
        // do something
        // use native submit or ajax submit, look at your needs.
        form.submit();
    }
});

Another example that use valid.form event to submit form.

$('#form1').on('valid.form', function(e){
    $(this).ajaxSubmit();
});