Validate html text input as it's typed

前端 未结 9 669
再見小時候
再見小時候 2020-11-27 16:36

What\'s the best way of validating an HTML text input as it\'s typed? All ways I know of doing it has some drawbacks:

  1. Using $.keypress you only

9条回答
  •  余生分开走
    2020-11-27 17:16

    In the jQuery world, it's common to leverage plug-ins for these validation tasks. Plug-ins can be relatively easy to use, and their popularity usually reflects in less bugs than code written from scratch.

    Input validation is usually split into categories, including:

    1) Correct input format / Input mask. for example, only A-Z, or say, 10 digit numbers.

    2) Content existence in a domain. For example, airport code or postal codes.

    For (1) you can use these relatively popular plug-ins:

    Digital Bush's Masked Input Plugin for Jquery. It has many options for customisation including spaces, eg:

    from Digital Bush website:

    $("#phone").mask("(999) 999-9999");
    

    The autoNumeric from decorplanit.com . They have a nice support for numeric, as well as currency, rounding, etc.

    adapted from autoNumeric website:

    $('#amountPaid').autoNumeric({aSep: '.', aDec: ','}); // eg, 9.000,00
    

    For (2), you can use, for example, jQuery UI's autocomplete, combined with server resource data, in a format like JSON. These are likely to require custom code to lock input, but you can still leverage plug-ins for the basic functionality, and focus on the specific business logic you are creating.

    Some text above adapted from two answers in other posts here and here.

提交回复
热议问题