简体   繁体   English

javascript正则表达式验证,如果没有内容

[英]javascript regex validation if no content

I have the following validation on a form field: 我在表单字段上进行了以下验证:

$(".controlsphone input").blur(function() {
    var ree = /^\d+$/;
    if(ree.test(document.getElementById("register_telephone").value))
        {
            $(this).css('border-color','green');
            $(this).siblings('.info').css('display','none');
            $(this).siblings('.error').css('display','none');
            $(this).siblings('.valid').css('display','inline-block');   
            $("#email_error401112").hide();
            $('#registerErrors').hide();
    }
    else
    {
        $('#registerErrors').show();
        $('#email_error401112').remove();
        $('#registerErrors').append('<p id="email_error401112">Please enter a phone number</p>');
    }
});

I would like to only validate the field if a number exists. 我想只在数字存在的情况下验证该字段。 The field is not required, but if there is content within the field, it needs to be valid (a number) 该字段不是必需的,但如果该字段中有内容,则该字段必须有效(数字)

How does the above code look? 上面的代码看起来如何? Any ideas what i can do to implement this? 有什么想法我可以做到这一点?

Cheers, Dan 干杯,丹

Use 采用

var ree = /^\d*$/;

because + stands for one or more, excluding zero. 因为+代表一个或多个,不包括零。

while * stands for zero or more *代表零或更多

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

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