使用jquery进行表单验证

时间:2014-02-09 10:36:02

标签: jquery

我正在尝试验证示例表单。我需要“名称”部分不要以数字开头。如果名称以数字开头,那么它将显示错误......我该怎么做?

<!DOCTYPE html>
<head>
 <script src="js/modernizr-2.5.3.min.js"></script>
 <script src="assets/js/jquery-1.7.1.min.js"></script>
 <script src="assets/js/bootstrap.min.js"></script>
 <script src="assets/js/jquery.validate.min.js"></script>
 <script src="assets/js/prettify/prettify.js"></script>
<script src="script.js"></script>
<script>
addEventListener('load', prettyPrint, false);
$(document).ready(function(){
$('pre').addClass('prettyprint linenums');
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-22151549-3']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') +   '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0];   s.parentNode.insertBefore(ga, s);})();
 </script>
 <body>
  <form action="" id="contact-form" class="form-horizontal">
  <label class="" for="name">Your Name</label>                          
  <input type="text" class="input-xlarge" name="name" id="name" >
  <br/>

  <label class="control-label" for="email">Email Address</label>
  <input type="text" class="input-xlarge" name="email" id="email">
  <br/>

<label class="control-label" for="subject">Subject</label>
<input type="text" class="input-xlarge" name="subject" id="subject">
<br/>

<label class="control-label" for="message">Your Message</label>
<textarea class="input-xlarge" name="message" id="message" rows="3"></textarea>
 <br/>

 <button type="submit" class="btn btn-primary btn-large">Submit</button>
 </form>
</body>
</html>

3 个答案:

答案 0 :(得分:1)

//returns number at the beginning or NAN
var validate = parseInt(formData);  

//if there was a number in front of the string, still the number
//if there was a NaN, this returns NaN
validate = +validate                

if (validate || validate === 0) {
  alert('Not a name!')
}
  

如果parseInt遇到的字符不是指定基数中的数字,它会忽略它和所有后续字符,并返回解析到该点的整数值。 parseInt将数字截断为整数值。允许前导和尾随空格。   MDN

答案 1 :(得分:1)

由于您使用的是html5 doctype,请执行以下操作。

替换<input type="text" class="input-xlarge" name="name" id="name" >

用这个

<input type="text" class="input-xlarge" name="name" id="name" pattern="^[^0-9].*" title="Cannot start with digit" />

这会奏效。这也会提醒用户。你不需要做任何事情。

如果有帮助,请将其标记为答案:)

答案 2 :(得分:1)

你可以这样做:

$(function()
{
    var str;
    $('#name').change(function()
    {
    str = ('#name').val();
    if(!isNaN(str[0])
    {
         alert('error') //of course you should change the error message ;)
    }
    });
});