[英]Javascript regex validation?
So I'm using the minimal regex [0-9]* for the iPhone number pad in my HTML5 pattern attributes. 因此,我在HTML5模式属性中为iPhone数字键盘使用了最小的正则表达式[0-9] *。 I also had a submit function that sends an email through the server.
我还有一个提交功能,可以通过服务器发送电子邮件。 Everything was working good until I realized it was trying to send the form re3gardless of whether the browser was trying to block submit based on incorrect user input.
一切运行良好,直到我意识到它试图重新发送表单,无论浏览器是否基于错误的用户输入来阻止提交。
So I did the following but can't get it to work: 所以我做了以下事情,但无法正常工作:
<script>
function validate(){
var phone=/[0-9]*/;
var x=document.forms["form"]["contactnum"].value;
if (x!=phone){
alert("Contact Number must be a valid phone number (no dashes)");
return false;
}
else {
alert("Thank you! We have received your information and will contact you shortly.");
ajax('{{=URL('new_post')}}',['phone'], 'target');
return false;
}
}
</script>
The problem is I can only get it to work if I set if (x==null || x=="") in the if statement. 问题是,只有在if语句中设置if(x == null || x ==“”)时,我才能使其工作。 If I try to match it with any other var it will always say I'm not matching the [0-9]*.
如果我尝试将其与其他任何var匹配,它将始终说我不匹配[0-9] *。 I already have written several complex regex's but really don't want to use anything on this simple form.
我已经写了一些复杂的正则表达式,但是真的不想在这种简单形式上使用任何东西。 I just wanted the number pad on the iPhone and not to submit if it wasn't a digit or null.
我只想要iPhone上的数字键盘,而不是数字或null而不提交。 I don't even care if they put in a "2" for the phone, just so long as it's a digit.
我什至不在乎他们是否在电话中输入“ 2”,只要是数字即可。
Thanks. 谢谢。
if ( x.match(/^[0-9]+$/) ) {
// valid
} else {
// invalid
}
That's not how you use a regular expression: 那不是您使用正则表达式的方式:
if (!phone.test(x)) ...
Also if you want to match a string with nothing but digits, try 另外,如果您想匹配只包含数字的字符串,请尝试
var phone = /^\d*$/;
That will match the empty string too; 那也将匹配空字符串; use
+
instead of *
if you want at least one digit. 如果要至少一位数字,请使用
+
而不是*
。
You actually seem to have two questions in one here. 您实际上似乎在这里有两个问题。 For the first part, you haven't shown how you're using
validate()
, but remember that the onsubmit handler, itself, must return false to keep the browser from completing the normal submit process. 对于第一部分,您没有显示如何使用
validate()
,但是请记住,onsubmit处理程序本身必须返回false,以防止浏览器完成正常的提交过程。 For example, the following will not work: 例如,以下将不起作用:
$('#myform').submit(function(){
validate();
});
But this would successfully stop the default submit process: 但这将成功停止默认的提交过程:
$('#myform').submit(function(){
return validate();
});
validate()
would return false, and then your handler returns the same. validate()
将返回false,然后您的处理程序将返回相同的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.