限制文本框来模式化和验证Jquery和PHP [英] Restrict Text Box to Pattern and validate Jquery and PHP

查看:109
本文介绍了限制文本框来模式化和验证Jquery和PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图设置一个文本框以限制新西兰驾驶员执照的格式,因此我一直在寻找正则表达式来验证这一点,但实际上我不确定如何做到这一点.

I'm trying to set up a text box to restrict to a format for a New Zealand Drivers Licence, so I've been looking in to regex to validate this, but I'm not actually sure how to do it.

该字段必须限制为2个字母,后跟6个数字(AA123456)

The field needs to be restricted to 2 letters followed by 6 numbers (AA123456)

到目前为止,我已经提出了从 http://www.regexr获得的模式/([A-Za-z]{2}\d{4})/. com/,但是在输入字段中查找了如何使用正则表达式后,我无法解决.我希望它在输入时进行验证,所以说他们输入AAB不会添加B.

So far I've come up with this pattern /([A-Za-z]{2}\d{4})/ which I got from http://www.regexr.com/, but after looking around for how to use regex in the input field I can't work it out. I'm wanting it to validate as they type, so say they type AAB it won't add the B.

到目前为止,我的代码:

My code so far:

$("#licenceNo").keyup(function() {
    var data = $("#licenceNo").val().match(/([A-Za-z]{2}\d{6})/);
}

但是我不确定下一步该怎么做...

But I'm not sure what to do next...

我还想使用PHP验证此服务器端.我只是使用相同的表达式吗?

I also want to validate this server side using PHP. Do I just use the same expression?

任何人都可以发布教程链接吗?搜索时我所能找到的只是EDU论文.

Can anyone post links to tutorials? All I can find when I search is EDU papers.

推荐答案

与服务器端验证相比,客户端方法可能更有意义.我想不出为什么您需要在PHP中执行此操作.

A client side approach probably makes more sense than doing server side validation. I can't think of why you'd need to do this in PHP.

如果该字符与您的模式不匹配,该方法将使您删除最后一个字符,并将文本框设置为红色.否则,它将被设置为绿色,并让您继续输入.

This approach will let you remove the last character if it doesn't match your pattern and set the textbox to red. Otherwise, it will be set it to green and let you continue typing.

$("#licenseNo").on("change keyup", function() {
    isValid = isValidLicenseNo(this.value);
    if (isValid) {
        $(this).css( "background-color", "green" );
    } else {
        $(this).val($(this).val().slice(0,-1));
        $(this).css( "background-color", "red" );
    }
});
function isValidLicenseNo(text) {
    if(text.length < 2) return text.match(/(^[A-Za-z]{0,1})$/);
    return text.match(/(^[A-Za-z]{2}\d{0,6}$)/);
}

这是 JS小提琴

我必须对您的RegEx进行一些修改. '^'和'$'锚点可防止用户在初始匹配后无限期地添加字符.十进制匹配后的范围('\ d {0,6}')可帮助车牌在用户仍在键入时进行匹配.获得与0-1字符大小写正确匹配的RegEx很难,因此我作弊并编写了单独的RegEx.

I had to make some modification to your RegEx. The '^' and '$' anchors prevent the user from adding characters indefinitely after the initial match. The range after your decimal match ('\d{0,6}') helps license plates match while the user is still typing them out. It was tricky to get a RegEx that correctly matched for the 0-1 character case so I cheated on that and wrote a separate RegEx.

这篇关于限制文本框来模式化和验证Jquery和PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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