输入字段:限制键入的字母和数字的数量

时间:2015-09-04 14:34:24

标签: javascript jquery forms

有没有办法限制允许输入到输入字段的字母和数字的数量?我想只允许输入3个字母和2个数字,无论顺序如何。

这可以使用jQuery Mask Plugin吗?或者不是?

在这里查看我的jsFiddle:http://jsfiddle.net/0akoL2x2/

HTML:

<input type="text" class="preview" size="30" placeholder="Preview text" class="text-input" maxlength="5" autofocus />

jquery的:

jQuery('.personalisation').mask("XXXZZ", {
        translation: {
            'X': {pattern: /[A-Za-z0-9]/},
            'Z': {pattern: /[A-Za-z0-9]/},
    }

4 个答案:

答案 0 :(得分:1)

如何使用数据属性?我们称之为data-temp

<input type="text" class="alnum" maxlength="5" data-temp="">

使用$(document).on('input'...监控所有更改(甚至是动态元素),如果新值超过最大值,则立即恢复。否则,让它发生,并将data-temp更新为此新值。

$(document).on('input', '.alnum', function(){
    var txt = $(this).val();
    if(
        txt.replace(/[^0-9]/g,"").length > 2 ||
        txt.replace(/[^A-Za-z]/g,"").length > 3 ||
        txt.replace(/[a-zA-Z0-9]/g,"").length != 0
      ){
        $(this).val( $(this).data('temp') );
        return;
    }
    $(this).data('temp', txt);
});

JSFiddle demo

答案 1 :(得分:1)

这是一个有效的小提琴: http://jsfiddle.net/igorshmigor/k2ss62gg/3/

JS代码如下所示:

var numberCountLimit = 2;
var letterCountLimit = 3;
$(document).ready(function() {
 $('.preview').keypress(function(key) {
     if (key.charCode == 0){
         return true; 
     }
     var current = $(this).val();
     var filtered = current.replace(/[^a-z0-9]/gmi,'');
     $(this).val(filtered);
     var digits = filtered.replace(/[^0-9]/gmi,'');
     var alpha = filtered.replace(/[^a-z]/gmi,'');
     var digitCount = digits.length;
     var alphaCount = alpha.length;
     var isNumber = false;
     var isAlpha = false;
     if (key.charCode > 47 && key.charCode < 58){
         isNumber = true;
         if (digitCount >= numberCountLimit){
            return false; // too many digits
         }
     }
     if (key.charCode > 64 && key.charCode < 123){
         isAlpha = true;
         if (alphaCount >= letterCountLimit){
            return false; // too many letters
         }
     }
     if (!isAlpha && !isNumber){
         return false; 
     }
 });
});

P.S。:我不认为只需使用jQuery Mask插件即可完成。

答案 2 :(得分:0)

怎么样,你勾住按键并检查数字/字母计数器,如果超过你就会忽略按键(通过返回false)

public class ContactListFragment extends ListFragment {

    private ArrayList<Contact> mContacts;
    private static final String TAG = "CrimeListFragment";
    SeparatedListAdapter adapter2;
    ListView list;

    @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
    getActivity().setTitle(R.string.contact_title);
    mContacts = ContactLab.get(getActivity()).getContacts();

    adapter2 = new SeparatedListAdapter(getActivity()); 
    organizeList();
    }
     @Override
public void onResume(){
    super.onResume();
    mContacts = ContactLab.get(getActivity()).getContacts();
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.contact_contact_list, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()){
    case R.id.menu_item_new_contact:
    Contact contact = new Contact();
    ContactLab.get(getActivity()).addContact(contact);
    Intent i = new Intent(getActivity(), ContactActivity.class);
    i.putExtra(ContactFragment.EXTRA_CONTACT_ID_CF, contact.getmId());
    startActivityForResult(i, 0);
    return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

public void organizeList(){

    ArrayList<ArrayList> arrayLists = new ArrayList<ArrayList>();

         char firstChar;
        int firstIndex=0;
        int secondIndex=1;   

      for(int i=firstIndex; i<mContacts.size();){

          ArrayList<String> names = new ArrayList<String>();
          names.add(mContacts.get(i).getmName());
          if(i == mContacts.size()-1){
              arrayLists.add(names);
              firstIndex++;
          }
          firstChar = mContacts.get(i).getmName().charAt(0);
          innerloup:
          for(int ii=secondIndex; ii<mContacts.size();){
              if(firstChar == mContacts.get(ii).getmName().charAt(0)){
                  names.add(mContacts.get(ii).getmName());
                  secondIndex++;
                 if(secondIndex == mContacts.size())
                 {
                     firstIndex = secondIndex;
                     arrayLists.add(names);
                 }
              }
              else{


                  arrayLists.add(names); 
                firstIndex = secondIndex;
                secondIndex++;
                 ii=secondIndex;
                break innerloup;

              }
         ii=secondIndex;
          }
        i = firstIndex;
      }


     for(int i =0; i<arrayLists.size(); i++)
     {
        ArrayList<String> array = arrayLists.get(i);
        String name = array.get(0);
        char charFirst = name.charAt(0);
         adapter2.addSection(Character.toString(charFirst), new ArrayAdapter<String>(getActivity(),  
      R.layout.list_item, arrayLists.get(i)));  
     }

            setListAdapter(adapter2);



        }  
} 

答案 3 :(得分:0)

为您的文本框添加ID。

$("#box").mask('XXXZZ', {'translation': {
         X: {pattern: /[A-Za-z0-9]/}, 
         Z: {pattern: /[A-Za-z0-9]/}                                       
     }
});

JSFiddle