0

如何在使用 jquery 提交表单时验证文本字段以显示警报消息,如果文本字段包含非键盘特殊字符(如 ascii 字符形式 127-255 和 iso-8859-1 字符)

示例代码:

Javascript代码:

<script type="text/javascript">
    $(function()
    {           
        $('#send').click(function()
        {
            var firstname=$('#firstname').val();
            var pattern = "^[a-zA-Z0-9~`!@#$%^&*()_+-={}|:;<>,.?\/']+$";
            if((!firstname.match(pattern)))
            {
                alert('your input contained not supported characters');
                return false;
            }
            return true;
        });
    });
</script>

html代码:

<form id="ajax_form" action="ajaxoutput.php">
<input type="text" name="FirstName" id="firstname" placeholder="FirstName" /><br>
<input type="text" name="LastName" placeholder="LastName" /><br>
<input type="file" name="image"/><br/>
<input type="submit" value="submit" name="submit" id="send" /> <input type="reset" value="reset"/>
</form>
4

1 回答 1

0

You are passing a string as .match() argument whilke it need a regular expression.

To create a regexp, you can do this :

var pattern = new RegExp("^[a-zA-Z0-9~`!@#$%^&*()_+-={}|:;<>,.?\/']+$");

or

var pattern = /^[a-zA-Z0-9~`!@#$%^&*()_+-={}|:;<>,.?\/']+$/;

Then match will work!

Since you use a lot of special character, you'll probly need to escape some of them aswell (with \).

于 2013-06-14T13:06:32.153 回答