dongqu7778 2012-02-11 20:37
浏览 24
已采纳

Javascript和PHP正则表达式验证

I am making an form on my website but I have an problem with 2 regexs. (I have an PHP regex and an JS regex because I read that javascript only is dangerous)

First is in PHP

$name = mysql_real_escape_string($_POST['name']);
                    if(strlen($name) < 2 || strlen($name) > 20 || preg_match('#[0-9]#',$name))
                    {   
                        echo '<p class="center"> je naam: <b> '.$name.' </b>  bevat cijfers en/of mag niet korter zijn dan 2 tekens en niet langer zijn dan 20 tekens. </p>';                   
                        echo '<p class="center"> <a href="javascript:history.go(-1);">Ga terug</a></p> ';
                    }

this preg_match give's an error if there are numbers in the name. The question is I dont want that people have &^*#@ and that things in there name.

What is the correct regex for that.

Next is Javascript

function checkform ( form )
    {
        if (form.name.value == "") 
        {
            alert( "Please enter your name." );
            form.name.focus();
            return false ;
        }

        if (form.email.value == "")
        {
            alert( "Please enter your email address." );
            form.email.focus();
            return false ;
        }

        return true ;
    }

Here I want the same thing and validate that checks emptyness and length and no #$^&!

For email validate I need another regex but i search that one later.

Greeting Jochem

Please edit if you see mistakes.

EDIT:

var re and var regex are email regexs that i found. But why wont they work kan someone give me an good answer with explination because i am not so good. :)

function checkform ( form )
    {
        var rex = /[^a-z]/i;
        var regex = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        var re = /^(([^<>()[\]\\.,;:\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,}))$/;

        if (regex.test(form.email.value))
        {
            alert( "Please enter your email address." );
            form.email.focus();
            return false ;
        }

        if (rex.test(form.name.value)) 
        {
            alert( "Please enter your name. no numbers or #$^& things allowed)." );
            form.name.focus();
            return false ;
        }

        return true ;
    }
  • 写回答

1条回答 默认 最新

  • doujingdai5521 2012-02-11 20:40
    关注

    If you only want to accept letters, use /[^a-z]/i. You can use this regex in PHP and in JavaScript.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于logstash转发日志时发生的部分内容丢失问题
  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?