[英]Javascript validation in Form runat=server
I'm new to .NET and web development in general. 我是.NET和Web开发的新手。 I created a form to collect a user's comment and/or a file attachment. 我创建了一个表单来收集用户的评论和/或文件附件。 Everything works fine but I would like to add client side validation but it fails when I do so. 一切正常,但我想添加客户端验证,但这样做会失败。 Using Chrome's dev tools I can see the javascript is executed but the first statement fails saying "cannot read property value of undefined". 使用Chrome的开发工具,我可以看到javascript已执行,但是第一条语句失败,提示“无法读取未定义的属性值”。 If I remove the runat="server" properties, it works fine but I can no longer access the data from the code behind. 如果删除runat =“ server”属性,则可以正常工作,但无法再通过后面的代码访问数据。
So what options do I have for making the javascript work? 那么我有什么选择可以使javascript工作呢? Or am I going about saving the data the wrong way? 还是我会以错误的方式保存数据?
aspx page: aspx页面:
<form id="commentForm" name="commentForm" runat="server" enctype="multipart/form-data" method="post" onsubmit="return validateCommentForm()">
<p>Add Comment</p>
<textarea id="Comment" name="Comment" rows="4" class="with-100" runat="server" />
<input id="FileAttachment" type="file" runat="server" />
<input type="submit" id="SaveComment" class="red-button" value="Submit" />
</form>
javascript: JavaScript的:
function validateCommentForm()
{
var x = document.commentForm.Comment.value;
var y = document.commentForm.FileAttachment.value;
if (x == '' && y == '')
{
alert("Either a commment or file must be supplied.");
return false;
}
}
c#: C#:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == true)
{
if (Comment.Value.Length > 0)
{
Insert.UserComment(Comment.Value);
}
HttpPostedFile UserFileAttachment = Request.Files[0];
if (UserFileAttachment.ContentLength > 0)
{
Insert.FileAttachment(UserFileAttachment);
}
}
}
Thanks in advance. 提前致谢。
You can use jQuery, where you can call the form elements by the name as described in their API . 您可以使用jQuery,在其中您可以按其API中所述的名称来调用表单元素。
Retrieve the value: 检索值:
$("input[name='Comment']").val();
To update the value (if needed) from JavaScript: 要从JavaScript更新值(如果需要):
$("input[name='Comment']").val('some Comment');
You can also do it by ID (and based on your sample this should work) with the following jQuery: 您还可以使用以下jQuery通过ID(并且应基于您的示例)进行操作:
$("#Comment").val();
So your final JavaScript would look like: 因此,您的最终JavaScript如下所示:
function validateCommentForm()
{
var x = $("#Comment").val();
var y = $("#FileAttachment").val();
if (x == '' && y == '')
{
alert("Either a commment or file must be supplied.");
return false;
}
}
I do think there's something odd in accessing the file name from a file input box. 我确实认为从文件输入框访问文件名有些奇怪。 See the file selector jQuery documentation . 请参阅文件选择器jQuery 文档 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.