jquery / JS只允许数字&在textfield中的字母 [英] jquery / JS allow only numbers & letters in a textfield

查看:113
本文介绍了jquery / JS只允许数字&在textfield中的字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在文本框中只允许字母/数字的最简单方法是什么?我们使用JS / jQuery,但不想使用验证插件?

What would be the easiest way to allow only letters/numbers in a textbox. We are using JS/jQuery, but don't want to use a validation plugin?

推荐答案

您可以使用简单的正则表达式表单提交以评估文本框的内容,显示错误并停止表单提交。从检查中取出一个功能,当文本框失去焦点时,您也可以应用它。

You can use a simple regex on form submit to evaluate the contents of the text box, show an error, and stop the form submit. Make a function out of the check and you can also apply it when the text box loses focus. Do this very often and you'll find that you've reimplemented the validation plugin.

$(function() {
    $('form').submit( function() {
        return validateTB( $('#textbox'), true, $('#textboxError') );
    });

    $('#textbox').blur( function() {
        validateTB( $(this), true, $('#textboxError') );
    });

    function validateTB(tb,required,msg) {
        var $tb = $(tb);
        var re = '/^[a-z0-9]';
        if (required) {
           re += '+';
        }
        else {
           re += '*';
        }
        re += '$/';

        if ($tb.val().match(re) == null) {
           $(msg).show();
           return false;
        }
        $(msg).hide();
        return true;
    }
});

这篇关于jquery / JS只允许数字&在textfield中的字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆