简体   繁体   English

用于客户端和服务器端验证的正则表达式相同

[英]Same regex for client-side and server-side validation

I am trying to find out whether my client-side Javascript regex 我试图找出我的客户端Javascript正则表达式

/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/

for email validation (I'm using it just to make sure that the email is formatted properly, not as a primary validation method) will work on the server side with PHP. 用于电子邮件验证(我使用它只是为了确保电子邮件的格式正确,而不是作为主要的验证方法)将在PHP的服务器端运行。

I am not sure whether I can use the same one even though both languages use Perl-based regex syntax. 我不确定即使两种语言都使用基于Perl的regex语法,我是否也可以使用相同的语言。 Thank you for your help. 谢谢您的帮助。

You should be able to use the same syntax. 您应该能够使用相同的语法。 You should use preg_match(String $pattern, String $email[, array $matches]) with your pattern. 您应该将preg_match(String $ pattern,String $ email [,array $ matches])与您的模式一起使用。 It puts all occurrences into the array $matches, if given. 如果给定,它将所有匹配项放入数组$ matches中。 It returns true if a match is found. 如果找到匹配项,则返回true。 For E-Mails in particular it's always a better idea to use the functions of others, because for example "$@us" is a valid email address 特别是对于电子邮件,最好使用其他功能,因为例如“ $ @ us”是有效的电子邮件地址。

This regex will work nearly identically in both JavaScript and PHP. 这个正则表达式将在JavaScript和PHP中几乎完全相同。 There are some minuscule differences, for example \\s matches the "next line" control character U+0085 in PHP, but not in JavaScript, but they are unlikely to matter in this context (it's unusual anyway to allow newlines and tabs in email addresses - why not use a simple space instead of the generic whitespace shorthand \\s ). 有一些细微的差异,例如\\s匹配PHP中的“下一行”控制字符U+0085 ,但在JavaScript中不匹配,但是在这种情况下它们不太重要(反正在电子邮件地址中允许使用换行符和制表符-为什么不使用简单的空格而不是通用的空白速记\\s

If you have to do these kinds of comparisons/conversions regularly, I heartily recommend you taking a look at RegexBuddy which can convert regexes between flavors with a single click. 如果您必须定期进行这些比较/转换,我强烈建议您看一下RegexBuddy ,它只需单击一下即可在各种口味之间转换正则表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM