我有一个要验证的表格(下面的片段)
<form action="" class="form-horizontal contact-form">
<h2>Contact details</h2>
<h3>Please ensure that these are accurate so that we can contact you if there is a problem processing your request</h3>
<fieldset>
<div class="control-group">
<label class="control-label" for="first-name">First name<span class="asterisk">*</span>:</label>
<div class="controls">
<input type="text" id="first-name" name="first-name" placeholder="Please enter your first name" />
</div>
</div>....
我无法让我的验证函数工作,并且对通过函数传递“e”作为参数感到好奇(如果这有意义的话)......
一直在为此绞尽脑汁,希望有人能发现我哪里出错了
JS如下:
(function(){
var form = '.contact-form',
alert = $('.alert'),
fieldWrap = '.control-group',
error = 'error',
errorMsg = 'error-message',
show = 'show',
hide = 'hide',
formValid = false;
var validate = function(field,regEx,e){
if((regEx).test($(field).val())){
$(field).parents(fieldWrap).addClass(error).find(errorMsg).addClass(hide);
formValid = true;
}
else{
$alert.addClass(show);
$(field).parents(fieldWrap).removeClass(error).find(errorMsg).addClass(show);
e.preventDefault();
e.stopPropagation();
}
};
$(form).on('submit',function(e){
validate('#first-name',/^[a-zA-Z]{3}/,e);
validate('#last-name',/^[a-zA-Z]{3}/,e);
validate('#contact-number',/^[a-zA-Z]{3}/,e);
validate('#email',/^[a-zA-Z]{3}/,e);
validate('#landline-number',/^[a-zA-Z]{3}/,e);
validate('#postcode',/^[a-zA-Z]{3}/,e);
});
})();
正则表达式只是为了测试字段。