简体   繁体   English

如何使用jquery编写条件语句来验证页面网址或电子邮件?

[英]How do I write a conditional statement using jquery that validates a page url or an email?

I have two regular expressions for one user input field that should accept a websites contact page url or an email address. 对于一个用户输入字段,我有两个正则表达式,它们应该接受网站的联系页面网址或电子邮件地址。 How can I write this in Jquery or Javascript? 如何用Jquery或Javascript编写此代码? Here are my two regular expressions. 这是我的两个正则表达式。

regex for URL "((www\.|(http|https|ftp|news|file)+\:\/\/)[&#95;.a-z0-9-]+\.[a-z0-9\/&#95;:@=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])",


regex for email "^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$",

 error messageelse "You must enter a valid email or you must enter a valid url, which starts with http://. The www prefix is optional.")

Demo - http://jsfiddle.net/A77fD/ 演示-http://jsfiddle.net/A77fD/

Example - 范例-

var url_regex = /((www\.|(http|https|ftp|news|file)+\:\/\/)[&#95;.a-z0-9-]+\.[a-z0-9\/&#95;:@=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])/;
var email_regex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/

$('#test').click(function(){
    console.log(url_regex.test($('#test_field').val()));
    console.log(email_regex.test($('#test_field').val()));

    if(!(url_regex.test($('#test_field').val()) || email_regex.test($('#test_field').val()))){
        alert("You must enter a valid email or you must enter a valid url, which starts with http://. The www prefix is optional.")
    }
})

use regex.test("url or email") 使用regex.test(“ URL或电子邮件”)

var regexU = /((www\.|(http|https|ftp|news|file)+\:\/\/)[&#95;.a-z0-9-]+\.[a-z0-9\/&#95;:@=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])/;
var regexEmail = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/

function validate() {
    if( regexUrl.test("url") || regexEmail.test("email")) {
    console.log("valid"); 
    } else {
      console.log("You must enter a valid email or you must enter a valid url, which starts with http://. The www prefix is optional.");
    }
}

I'd recommend using some kind of library to do your validations. 我建议使用某种库进行验证。 No need to reinvent the wheel every time. 无需每次都重新发明轮子。

jQuery has a plugin that could be suitable: http://rocketsquared.com/wiki/Plugins/Validation jQuery有一个适合的插件: http : //rocketsquared.com/wiki/Plugins/Validation

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

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