How can i use preg_match in jQuery?

老子叫甜甜 提交于 2019-11-30 17:44:26

问题


Can i use preg_match to validate phone number in jQuery? Here is my code which does not work

if (!preg_match("/^[0-9]{3}-|\s[0-9]{3}-|\s[0-9]{4}$/", phone.val() ))  {
            phone.addClass("needsfilled");
            phone.val(phonerror);
        }

HTML <input id="phone" type="text" value="" name="phone" />

Could any one help plz


回答1:


Javascript includes a regular expression engine, which is accessed via the string.match(), string.replace() and string.split() functions.

For example:

var mystring = "this is a sentence";
mystring = mystring.replace(/sentence/,'string');

var matches = mystring.match(/\b\w+\b/);

That should provide you with essentially the same functionality as preg_match().

So to do the same validation as the preg_match in your question:

if(!phone.val().match(/^[0-9]{3}-|\s[0-9]{3}-|\s[0-9]{4}$/)) {
     phone.addClass("needsfilled");
     phone.val(phonerror);
}

If you absolutely insist on having a function called preg_match() which works exactly like the PHP version, there is a project called PHPJS, which aims to implement PHP functions in Javascript. A quick look at their site shows that although they don't currently have a fully working preg_match() implementation, they have an unfinished implementation which you may want to look at. But frankly, the built-in Javascript .match() function should be more than sufficient.




回答2:


To use a PHP function, you will have to make an HTTP request to the server (with whatever data you want to test) and then parse the response.

Better to use JavaScript's native regular expression functionality.




回答3:


RegExp.exec(string) will work.

try this:

var pattern= "/your pattern/";
var result = pattern.exec ( $("#phone").val() );
// true if match

src: http://javascriptkit.com/javatutors/redev3.shtml




回答4:


Instead of using preg_match, which is a PHP function, you should use the String object's match function. See the Mozilla docs for information on using the match function.



来源:https://stackoverflow.com/questions/6031468/how-can-i-use-preg-match-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!