Маска для полей формы.маски ввода для текстовых полей

Usage:

Include the js-files which you can find in the folder.

via Inputmask class

<scriptsrc="jquery.js"><script><scriptsrc="inputmask.js"><script><scriptsrc="inputmask.???.Extensions.js"><script>
var selector =document.getElementById("selector");var im =newInputmask("99-9999999");im.mask(selector);Inputmask({"mask""(999) 999-9999",....other options .....}).mask(selector);Inputmask("9-a{1,3}9{1,3}").mask(selector);Inputmask("9",{ repeat10}).mask(selector);

via jquery plugin

<scriptsrc="jquery.js"><script><scriptsrc="inputmask.js"><script><scriptsrc="inputmask.???.Extensions.js"><script><scriptsrc="jquery.inputmask.js"><script>

or with the bundled version

<scriptsrc="jquery.js"><script><scriptsrc="jquery.inputmask.bundle.js"><script>
$(document).ready(function(){$(selector).inputmask("99-9999999");$(selector).inputmask({"mask""(999) 999-9999"});$(selector).inputmask("9-a{1,3}9{1,3}");});

via data-inputmask attribute

<inputdata-inputmask="'alias': 'date'" /><inputdata-inputmask="'mask': '9', 'repeat': 10, 'greedy' : false" /><inputdata-inputmask="'mask': '99-9999999'" />
$(document).ready(function(){$(":input").inputmask();  orInputmask().mask(document.querySelectorAll("input"));});

Any option can also be passed through the use of a data attribute. Use data-inputmask-<the name of the option>=»value»

<inputid="example1"data-inputmask-clearmaskonlostfocus="false" /><inputid="example2"data-inputmask-regex="[a-za-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:(?:*)?\.)+(?:*)?" />
$(document).ready(function(){$("#example1").inputmask("99-9999999");$("#example2").inputmask("Regex");});

If you like to automatically bind the inputmask to the inputs marked with the data-inputmask- … attributes you may also want to include the inputmask.binding.js

...<scriptsrc="inputmask.binding.js"><script>...

If you use a module loader like requireJS

Have a look at the inputmask.loader.js for usage.

Example config.js

paths{..."inputmask.dependencyLib""../dist/inputmask/inputmask.dependencyLib","inputmask""../dist/inputmask/inputmask",...}

As dependencyLib you can choose between the supported libraries.

  • inputmask.dependencyLib (vanilla)
  • inputmask.dependencyLib.jquery
  • inputmask.dependencyLib.jqlite
  • …. (others are welcome)
  • (and all others supported by contenteditable)
  • any html-element (mask text content or set maskedvalue with jQuery.val)
  • : numeric
  • : alphabetical
  • : alphanumeric

There are more definitions defined within the extensions.You can find info within the js-files or by further exploring the options.

Initialization

ES2015 (Webpack/Rollup/Browserify/etc)

import Vue from 'vue'

// As a plugin
import VueMask from 'v-mask'
Vue.use(VueMask);

// Or as a directive
import { VueMaskDirective } from 'v-mask'
Vue.directive('mask', VueMaskDirective);

// Or only as a filter
import { VueMaskFilter } from 'v-mask'
Vue.filter('VMask', VueMaskFilter)

UMD (Browser)

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/v-mask/dist/v-mask.min.js"></script>
<script>
// As a plugin
Vue.use(VueMask.VueMaskPlugin);

// Or as a directive
Vue.directive('mask', VueMask.VueMaskDirective);
</script>

Usage:

Include the js-files which you can find in the dist-folder. You have the bundled file which contains the main plugin code and also all extensions. (date, numerics, other) or if you prefer to only include some parts, use the separate js-files in the dist/min folder.

The minimum to include is the jquery.inputmask.js

<script src="jquery.js" type="text/javascript"></script>
<script src="jquery.inputmask.js" type="text/javascript"></script>

Define your masks:

$(document).ready(function(){
   $("#date").inputmask("d/m/y");  //direct mask
   $("#phone").inputmask("mask", {"mask": "(999) 999-9999"}); //specifying fn & options
   $("#tin").inputmask({"mask": "99-9999999"}); //specifying options only
});

or

<input data-inputmask="'alias': 'date'" />
<input data-inputmask="'mask': '9', 'repeat': 10, 'greedy' : false" />
<input data-inputmask="'mask': '99-9999999'" />
$(document).ready(function(){
    $(":input").inputmask();
});

Default masking definitions

  • 9 : numeric
  • a : alfabetic

There are more definitions defined within the extensions.
You can find info within the js-files or by further exploring the options.

General

set a value and apply mask

this can be done with the traditional jquery.val function (all browsers) or JavaScript value property for browsers which implement lookupGetter or getOwnPropertyDescriptor

$(document).ready(function(){
   $("#number").val(12345);

   var number = document.getElementById("number");
   number.value = 12345;
});

with the autoUnmaskoption you can change the return of $.fn.val (or value property) to unmaskedvalue or the maskedvalue

$(document).ready(function(){
       $('#<%= tbDate.ClientID%>').inputmask({ "mask": "d/m/y", 'autoUnmask' : true});    //  value: 23/03/1973
    alert($('#<%= tbDate.ClientID%>').val());    // shows 23031973     (autoUnmask: true)

    var tbDate = document.getElementById("<%= tbDate.ClientID%>");
    alert(tbDate.value);    // shows 23031973     (autoUnmask: true)
});

auto upper/lower- casing inputmask

You can define within a definition to automatically lowercase or uppercase the entry in an input by giving the casing.Casing can be null, «upper» or «lower»

   Inputmask.extendDefinitions({
        'A': {
            validator: "",
            cardinality: 1,
            casing: "upper" //auto uppercasing
        },
        '+': {
            validator: "",
            cardinality: 1,
            casing: "upper"
        }
    });

Include jquery.inputmask.extensions.js for using the A and # definitions.

$(document).ready(function(){
   $("#test").inputmask("999-AAA");    //   => 123abc ===> 123-ABC
});

Methods:

mask(elems)

Create a mask for the input.

$(selector).inputmask({ mask: "99-999-99"});

or

Inputmask({ mask: "99-999-99"}).mask(document.querySelectorAll(selector));

or

Inputmask("99-999-99").mask(document.querySelectorAll(selector));

or

var im : new Inputmask("99-999-99");
im.mask(document.querySelectorAll(selector));

or

Inputmask("99-999-99").mask(selector);

unmaskedvalue

Get the

$(selector).inputmask('unmaskedvalue');

or

var input = document.getElementById(selector);
if (input.inputmask)
  input.inputmask.unmaskedvalue()

Value unmasking

Unmask a given value against the mask.

var unformattedDate = Inputmask.unmask("23/03/1973", { alias: "dd/mm/yyyy"}); //23031973

remove

Remove the .

$(selector).inputmask('remove');

or

var input = document.getElementById(selector);
if (input.inputmask)
  input.inputmask.remove()

or

Inputmask.remove(document.getElementById(selector));

getemptymask

return the default (empty) mask value

$(document).ready(function(){
  $("#test").inputmask("999-AAA");
  var initialValue = $("#test").inputmask("getemptymask");  // initialValue  => "___-___"
});

hasMaskedValue

Check whether the returned value is masked or not; currently only works reliably when using jquery.val fn to retrieve the value

$(document).ready(function(){
  function validateMaskedValue(val){}
  function validateValue(val){}

  var val = $("#test").val();
  if ($("#test").inputmask("hasMaskedValue"))
    validateMaskedValue(val);
  else
    validateValue(val);
});

isComplete

Verify whether the current value is complete or not.

$(document).ready(function(){
  if ($(selector).inputmask("isComplete")){
    //do something
  }
});

getmetadata

The metadata of the actual mask provided in the mask definitions can be obtained by calling getmetadata. If only a mask is provided the mask definition will be returned by the getmetadata.

$(selector).inputmask("getmetadata");

setvalue

The setvalue functionality is to set a value to the inputmask like you would do with jQuery.val, BUT it will trigger the internal event used by the inputmask always, whatever the case. This is particular usefull when cloning an inputmask with jQuery.clone. Cloning an inputmask is not a fully functional clone. On the first event (mouseenter, focus, …) the inputmask can detect if it where cloned an can reactivate the masking. However when setting the value with jQuery.val there is none of the events triggered. The setvalue functionality does this for you.

option(options, noremask)

Get or set an option on an existing inputmask.
The option method is intented for adding extra options like callbacks, etc at a later time to the mask.

When extra options are set the mask is automatically reapplied, unless you pas true for the noremask argument.

Set an option

document.querySelector("#CellPhone").inputmask.option({
  onBeforePaste: function (pastedValue, opts) {
    return phoneNumOnPaste(pastedValue, opts);
  }
});
$("#CellPhone").inputmask("option", {
  onBeforePaste: function (pastedValue, opts) {
    return phoneNumOnPaste(pastedValue, opts);
  }
})

format

Instead of masking an input element it is also possible to use the inputmask for formatting given values. Think of formatting values to show in jqGrid or on other elements then inputs.

var formattedDate = Inputmask.format("2331973", { alias: "dd/mm/yyyy"});
var isValid = Inputmask.isValid("23/03/1973", { alias: "dd/mm/yyyy"});

Quick Start

Include .

<script src="path/js/masking-input.js" data-autoinit="true"></script>`

Add either the css file to your page, or incorporate the .scss component into your sass build

<link rel="stylesheet" href="path/css/masking-input.css"/>

Add inputs with , and attributes with the class of . Include when requiring numbers only.

	 <label for="zip">Zip Code</label>
  	 <input id="zip" type="tel" placeholder="XXXXX" pattern="\d{5}" 
  	     class="masked" name="uszipcode" title="5-digit zip code"> 

If your placeholder includes non-digits and non-letters, no worries. They’ll be added by the script. Your mobile users won’t have to change their touch keyboards. They simply need to enter letters.

Do make sure that your placeholder would match the regular expression of your pattern if all the X’s were converted to integers.

If your regular expressions include letters, you must include the made up attribute. Similar to the pattern, include an for each number and an underscore for each required letter.

	<label for="zipca">Canadian Zip Code</label>
  	<input placeholder="XXX XXX" pattern="\w\d\w \d\w\d" class="masked" 
  		data-charset="_X_ X_X" id="zipca" type="text" name="zipcodeca" 
  	    title="6-character alphanumeric zip code in the format of A1A 1A1">

If the digits allowed by your regular expression are constrained or complicated, such as months only allowing 01-12, include a made up attribute that takes as its value a valid value that would match the pattern.

	<label for="expiration"> Credit Card Expiration </label>
    <input id="expiration" type="tel" placeholder="MM/YY" class="masked" 
    	pattern="(1|0)\/(1|2\d)" 
    	data-valid-example="05/18"> 

Masking types

Static masks

These are the very basic of masking. The mask is defined and will not change during the input.

$(document).ready(function(){
   $(selector).inputmask("aa-9999");  //static mask
   $(selector).inputmask({mask: "aa-9999"});  //static mask
});

Optional masks

It is possible to define some parts in the mask as optional. This is done by using .

Example:

$('#test').inputmask('(99) 9999-9999');

This mask wil allow input like (99) 99999-9999 or (99) 9999-9999.Input => 12123451234 mask => (12) 12345-1234 (trigger complete)Input => 121234-1234 mask => (12) 1234-1234 (trigger complete)Input => 1212341234 mask => (12) 12341-234_ (trigger incomplete)

skipOptionalPartCharacter

As an extra there is another configurable character which is used to skip an optional part in the mask.

skipOptionalPartCharacter: " ",

Input => 121234 1234 mask => (12) 1234-1234 (trigger complete)

When is set in the options (default), the mask will clear out the optional part when it is not filled in and this only in case the optional part is at the end of the mask.

For example, given:

$('#test').inputmask('999');

While the field has focus and is blank, users will see the full mask . When the required part of the mask is filled and the field loses focus, the user will see . When both the required and optional parts of the mask are filled out and the field loses focus, the user will see .

Optional masks with greedy false

When defining an optional mask together with the greedy: false option, the inputmask will show the smallest possible mask as input first.

$(selector).inputmask({ mask: "99999", greedy: false });

The initial mask shown will be «_» instead of «_-____».

Dynamic masks

Dynamic masks can change during the input. To define a dynamic part use { }.

{n} => n repeats{n,m} => from n to m repeats

Also {+} and {_} is allowed. + start from 1 and _ start from 0.

$(document).ready(function(){
   $(selector).inputmask("aa-9{4}");  //static mask with dynamic syntax
   $(selector).inputmask("aa-9{1,4}");  //dynamic mask ~ the 9 def can be occur 1 to 4 times

   //email mask
   $(selector).inputmask({
            mask: "*{1,20}@*{1,20}",
            greedy: false,
            onBeforePaste: function (pastedValue, opts) {
                pastedValue = pastedValue.toLowerCase();
                return pastedValue.replace("mailto:", "");
            },
            definitions: {
                '*': {
                    validator: "[0-9A-Za-z!#$%&'*+/=?^_`{|}~\-]",
                    cardinality: 1,
                    casing: "lower"
                }
            }
    });

Alternator masks

The alternator syntax is like an OR statement. The mask can be one of the 2 choices specified in the alternator.

To define an alternator use the |.ex: «a|9» => a or 9 «(aaa)|(999)» => aaa or 999

Also make sure to read about the keepStatic option.

$("selector").inputmask("(99.9)|(X)", {
                definitions: {
                    "X": {
                        validator: "",
                        cardinality: 1,
                        casing: "upper"
                    }
                }
            });

or

$("selector").inputmask({
                mask: "99.9", "X",
                definitions: {
                    "X": {
                        validator: "",
                        cardinality: 1,
                        casing: "upper"
                    }
                }
            });

Preprocessing masks

You can define the mask as a function which can allow to preprocess the resulting mask. Example sorting for multiple masks or retrieving mask definitions dynamically through ajax. The preprocessing fn should return a valid mask definition.

  $(selector).inputmask({ mask: function () { /* do stuff */ return "AAA-999", "999-AAA"; }});

Usage:

Include the js-files which you can find in the folder.

via Inputmask class

<script src="jquery.js"></script>
<script src="inputmask.js"></script>
<script src="inputmask.???.Extensions.js"></script>
var selector = document.getElementById("selector");

var im = new Inputmask("99-9999999");
im.mask(selector);

Inputmask({"mask": "(999) 999-9999", .... other options .....}).mask(selector);
Inputmask("9-a{1,3}9{1,3}").mask(selector);
Inputmask("9", { repeat: 10 }).mask(selector);

via jquery plugin

<script src="jquery.js"></script>
<script src="inputmask.js"></script>
<script src="inputmask.???.Extensions.js"></script>
<script src="jquery.inputmask.js"></script>

or with the bundled version

<script src="jquery.js"></script>
<script src="jquery.inputmask.bundle.js"></script>
$(document).ready(function(){
  $(selector).inputmask("99-9999999");  //static mask
  $(selector).inputmask({"mask": "(999) 999-9999"}); //specifying options
  $(selector).inputmask("9-a{1,3}9{1,3}"); //mask with dynamic syntax
});

via data-inputmask attribute

<input data-inputmask="'alias': 'date'" />
<input data-inputmask="'mask': '9', 'repeat': 10, 'greedy' : false" />
<input data-inputmask="'mask': '99-9999999'" />
$(document).ready(function(){
  $(":input").inputmask();
  or
  Inputmask().mask(document.querySelectorAll("input"));
});

Any option can also be passed through the use of a data attribute. Use data-inputmask-<the name of the option>=»value»

<input id="example1" data-inputmask-clearmaskonlostfocus="false" />
<input id="example2" data-inputmask-regex="[a-za-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:(?:*)?\.)+(?:*)?" />
$(document).ready(function(){
  $("#example1").inputmask("99-9999999");
  $("#example2").inputmask("Regex");
});

If you like to automatically bind the inputmask to the inputs marked with the data-inputmask- … attributes you may also want to include the inputmask.binding.js

...
<script src="inputmask.binding.js"></script>
...

If you use a module loader like requireJS

Add in your config.js

paths: {
  ...
  "inputmask.dependencyLib": "../dist/inputmask/inputmask.dependencyLib.jquery",
  "inputmask": "../dist/inputmask/inputmask",
  ...
}

As dependencyLib you can choose between the supported libraries.

  • inputmask.dependencyLib (vanilla)
  • inputmask.dependencyLib.jquery
  • inputmask.dependencyLib.jqlite
  • …. (others are welcome)

Allowed HTML-elements

  • (and all others supported by contenteditable)
  • any html-element (mask text content or set maskedvalue with jQuery.val)

Default masking definitions

  • : numeric
  • : alphabetical
  • : alphanumeric

There are more definitions defined within the extensions.You can find info within the js-files or by further exploring the options.

Overview

This is a masked input plugin for the jQuery javascript library. It allows a user to more easily enter fixed width input where you would like them to enter the data in a certain format (dates,phone numbers, etc). It has been tested on Internet Explorer, Firefox, Safari, Opera, and Chrome. A mask is defined by a format made up of mask literals and mask definitions. Any character not in the definitions list below is considered a mask literal. Mask literals will be automatically entered for the user as they type and will not be able to be removed by the user.The following mask definitions are predefined:

  • a — Represents an alpha character (A-Z,a-z)
  • 9 — Represents a numeric character (0-9)
  • * — Represents an alphanumeric character (A-Z,a-z,0-9)

First, include the jQuery and masked input javascript files.

    npm install jquery-inputmask --dev    or    yarn add jquery-inputmask

Next, call the mask function for those items you wish to have masked.

jQuery(function($){   $("#date").mask("99/99/9999");   $("#phone").mask("(999) 999-9999");   $("#tin").mask("99-9999999");   $("#ssn").mask("999-99-9999");});

Optionally, if you are not satisfied with the underscore (‘_’) character as a placeholder, you may pass an optional argument to the maskedinput method.

jQuery(function($){   $("#product").mask("99/99/9999",{placeholder:" "});});

Optionally, if you would like to execute a function once the mask has been completed, you can specify that function as an optional argument to the maskedinput method.

jQuery(function($){   $("#product").mask("99/99/9999",{completed:function(){alert("You typed the following: "+this.val());}});});

Optionally, if you would like to disable the automatic discarding of the uncomplete input, you may pass an optional argument to the maskedinput method

jQuery(function($){   $("#product").mask("99/99/9999",{autoclear: false});});

You can now supply your own mask definitions.

jQuery(function($){   $.mask.definitions='';   $("#eyescript").mask("~9.99 ~9.99 999");});

You can have part of your mask be optional. Anything listed after ‘?’ within the mask is considered optional user input. The common example for this is phone number + optional extension.

jQuery(function($){   $("#phone").mask("(999) 999-9999? x99999");});

If your requirements aren’t met by the predefined placeholders, you can always add your own. For example, maybe you need a mask to only allow hexadecimal characters. You can add your own definition for a placeholder, say ‘h’, like so: Then you can use that to mask for something like css colors in hex with a .

jQuery(function($){   $("#phone").mask("#hhhhhh");});

By design, this plugin will reject input which doesn’t complete the mask. You can bypass this by using a ‘?’ character at the position where you would like to consider input optional. For example, a mask of «(999) 999-9999? x99999» would require only the first 10 digits of a phone number with extension being optional.

Exceptions

Complex Regular Expressions

If the digits allowed by your regular expression are constrained or complicated, such as months only allowing 01-12, include a made up attribute that takes as its value a valid value that would match the pattern.

	<label for="expiration"> Credit Card Expiration </label>
    <input id="expiration" type="tel" placeholder="MM/YY" class="masked" 
    	pattern="(1|0)\/(1|2\d)" 
    	data-valid-example="11/18"
    	title="2-digit month and 2-digit year greater than 01/15"> 

I’ve taken care of MM in , because that is common. If you have exceptions, add the exceptions there. If you need an expiration month, it is best to use instead.

Supported markup options

data-inputmask attribute

You can also apply an inputmask by using the data-inputmask attribute. In the attribute you specify the options wanted for the inputmask. This gets parsed with $.parseJSON (for the moment), so be sure to use a well-formed json-string without the {}.

<input data-inputmask="'alias': 'date'" />
<input data-inputmask="'mask': '9', 'repeat': 10, 'greedy' : false" />
$(document).ready(function(){
  $(":input").inputmask();
});

data-inputmask-<option> attribute

All options can also be passed through data-attributes.

<input data-inputmask-mask="9" data-inputmask-repeat="10" data-inputmask-greedy="false" />
$(document).ready(function(){
  $(":input").inputmask();
});

Overview

This is a masked input plugin for the jQuery javascript library. It allows a user to more easily enter fixed width input where you would like them to enter the data in a certain format (dates,phone numbers, etc). It has been tested on Internet Explorer, Firefox, Safari, Opera, and Chrome. A mask is defined by a format made up of mask literals and mask definitions. Any character not in the definitions list below is considered a mask literal. Mask literals will be automatically entered for the user as they type and will not be able to be removed by the user.The following mask definitions are predefined:

  • a — Represents an alpha character (A-Z,a-z)
  • 9 — Represents a numeric character (0-9)
  • * — Represents an alphanumeric character (A-Z,a-z,0-9)

First, include the jQuery and masked input javascript files.

<scriptsrc="jquery.js"type="text/javascript"><script><scriptsrc="jquery.maskedinput.js"type="text/javascript"><script>

Next, call the mask function for those items you wish to have masked.

jQuery(function($){   $("#date").mask("99/99/9999");   $("#phone").mask("(999) 999-9999");   $("#tin").mask("99-9999999");   $("#ssn").mask("999-99-9999");});

Optionally, if you are not satisfied with the underscore (‘_’) character as a placeholder, you may pass an optional argument to the maskedinput method.

jQuery(function($){   $("#product").mask("99/99/9999",{placeholder:" "});});

Optionally, if you would like to execute a function once the mask has been completed, you can specify that function as an optional argument to the maskedinput method.

jQuery(function($){   $("#product").mask("99/99/9999",{completed:function(){alert("You typed the following: "+this.val());}});});

Optionally, if you would like to disable the automatic discarding of the uncomplete input, you may pass an optional argument to the maskedinput method

jQuery(function($){   $("#product").mask("99/99/9999",{autoclear: false});});

You can now supply your own mask definitions.

jQuery(function($){   $.mask.definitions='';   $("#eyescript").mask("~9.99 ~9.99 999");});

You can have part of your mask be optional. Anything listed after ‘?’ within the mask is considered optional user input. The common example for this is phone number + optional extension.

jQuery(function($){   $("#phone").mask("(999) 999-9999? x99999");});

If your requirements aren’t met by the predefined placeholders, you can always add your own. For example, maybe you need a mask to only allow hexadecimal characters. You can add your own definition for a placeholder, say ‘h’, like so: Then you can use that to mask for something like css colors in hex with a .

jQuery(function($){   $("#phone").mask("#hhhhhh");});

By design, this plugin will reject input which doesn’t complete the mask. You can bypass this by using a ‘?’ character at the position where you would like to consider input optional. For example, a mask of «(999) 999-9999? x99999» would require only the first 10 digits of a phone number with extension being optional.

Supported markup options

data-inputmask attribute

You can also apply an inputmask by using the data-inputmask attribute. In the attribute you specify the options wanted for the inputmask. This gets parsed with $.parseJSON (for the moment), so be sure to use a well-formed json-string without the {}.

<input data-inputmask="'alias': 'date'" />
<input data-inputmask="'mask': '9', 'repeat': 10, 'greedy' : false" />
$(document).ready(function(){
  $(":input").inputmask();
});

data-inputmask-<option> attribute

All options can also be passed through data-attributes.

<input data-inputmask-mask="9" data-inputmask-repeat="10" data-inputmask-greedy="false" />
$(document).ready(function(){
  $(":input").inputmask();
});
Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector