我有一个包含三个字段的表单:姓名、电子邮件地址和密码。现在我想阻止用户在值的开头输入空格“”,假设用户不能在字段中仅输入空格。
我尝试像这样修复它:
<script type="text/javascript">
function validate(){
if ((document.getElementById('fName').value) == '') {
alert('Please enter your first name');
return (false);
} else if ((document.getElementById('lName').value) == '') {
alert('Please enter your last name');
return (false);
} else {
return (true);
}
}
</script>
<form name="form1" id="form1" action="index.php" method="post">
<table align="right" border="0">
<tr>
<td>First Name:</td>
<td><input id="fName" name="fName" type="text" class="input-login"/></td>
</tr>
<tr><td>Email Address:</td></tr>
<tr><td><input id="email" name="email" type="text" class="input-login"/></td></tr>
<tr><td>Password:</td></tr>
<tr><td><input id="password" name="password" type="password" class="input-login"/>/td></tr>
<tr><td align="center"><a href="#">Forgot password</a></td></tr>
<tr>
<td align="center"><input name="login" id="login" type="submit" value="Login" >
<input name="signup" id="signup" type="submit" value="SignUp" ></td>
</tr>
</table>
</form>
但未能修复。
谁能帮帮我.. 谢谢。
最佳答案
自从您使用 jquery-validate
标记您的问题以来。这是如何使用 jquery 执行此操作的答案:
有关更多信息,请查看:http://docs.jquery.com/Plugins/Validation
<script type="text/javascript">
$.validator.addMethod("NoWhiteSpaceAtBeginn", function(value, element) {
return this.optional(element) || /^[^\t].*/.test(value);
}, "Must not begin with a whitespace");
$(document).ready(function(){
$("#form1").validate();
});
</script>
/^[^\t].*/
检查字符串是否以除空格之外的任何字符开头,如果要排除所有空格,请使用 /^[^\s ].*/
代替。
现在将 required
和 NoWhiteSpaceAtBeginn
作为类名称添加到您要验证的字段中。
<form name="form1" id="form1" action="index.php" method="post">
<table align="right" border="0">
<tr>
<td>First Name:</td>
<td><input id="fName" name="fName" type="text" class="input-login required NoWhiteSpaceAtBeginn"/></td>
</tr>
<tr><td>Email Address:</td></tr>
<tr><td><input id="email" name="email" type="text" class="input-login required NoWhiteSpaceAtBeginn email"/></td></tr>
<tr><td>Password:</td></tr>
<tr><td><input id="password" name="password" type="password" class="input-login"/>/td></tr>
<tr><td align="center"><a href="#">Forgot password</a></td></tr>
<tr>
<td align="center"><input name="login" id="login" type="submit" value="Login" > <input name="signup" id="signup" type="submit" value="SignUp" ></td>
</tr>
</table>
</form>
可以在这里找到一个很好的教程:http://corpocrat.com/2009/07/15/quick-easy-form-validation-tutorial-with-jquery/
关于javascript - 如何防止用户在文本框中开头输入空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2809311/