我有一个带有一些TextBox的jsp页面.现在我想填写一些信息,然后单击"提交"按钮.但是我需要检查这个TextBox是否为空.
我怎样才能做到这一点?
swe*_*ing 14
使用regexp:\ S将匹配非空白字符:除了空格,制表符或新行之外的任何内容.如果你的字符串有一个不是空格,制表符或新行的单个字符,那么它不是空的.因此,您只需要搜索一个字符:\ S.
JavaScript的:
function checkvalue() {
var mystring = document.getElementById('myString').value;
if(!mystring.match(/\S/)) {
alert ('Empty value is not allowed');
return false;
} else {
alert("correct input");
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
HTML:
<form onsubmit="return checkvalue(this)">
<input name="myString" type="text" value='' id="myString">
<input type="submit" value="check value" />
</form>
Run Code Online (Sandbox Code Playgroud)
Canonical没有使用框架,为旧浏览器添加了修剪原型
<html>
<head>
<script type="text/javascript">
// add trim to older IEs
if (!String.trim) {
String.prototype.trim = function() {return this.replace(/^\s+|\s+$/g, "");};
}
window.onload=function() { // onobtrusively adding the submit handler
document.getElementById("form1").onsubmit=function() { // needs an ID
var val = this.textField1.value; // 'this' is the form
if (val==null || val.trim()=="") {
alert('Please enter something');
this.textField1.focus();
return false; // cancel submission
}
return true; // allow submit
}
}
</script>
</head>
<body>
<form id="form1">
<input type="text" name="textField1" value="" /><br/>
<input type="submit" />
</form>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
这是内联版本,虽然不推荐我在这里显示,以防你需要添加验证而不能重构代码
function validate(theForm) { // passing the form object
var val = theForm.textField1.value;
if (val==null || val.trim()=="") {
alert('Please enter something');
theForm.textField1.focus();
return false; // cancel submission
}
return true; // allow submit
}
Run Code Online (Sandbox Code Playgroud)
传递表单对象(this)
<form onsubmit="return validate(this)">
<input type="text" name="textField1" value="" /><br/>
<input type="submit" />
</form>
Run Code Online (Sandbox Code Playgroud)
使用此JavaScript将对您有所帮助.代码中给出了一些解释.
<script type="text/javascript">
<!--
function Blank_TextField_Validator()
{
// Check whether the value of the element
// text_name from the form named text_form is null
if (!text_form.text_name.value)
{
// If it is display and alert box
alert("Please fill in the text field.");
// Place the cursor on the field for revision
text_form.text_name.focus();
// return false to stop further processing
return (false);
}
// If text_name is not null continue processing
return (true);
}
-->
</script>
<form name="text_form" method="get" action="#"
onsubmit="return Blank_TextField_Validator()">
<input type="text" name="text_name" >
<input type="submit" value="Submit">
</form>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
150707 次 |
| 最近记录: |