简体   繁体   English

必填字段的Javascript验证

[英]Javascript Validation for required fields

I am learning javascript and in a form validation example I found this : To check for required field 我正在学习javascript,并在表单验证示例中找到了这一点:检查必填字段

var x=document.forms["myForm"]["fname"].value;
 if (x==null || x=="")
   {
   alert("First name must be filled out");
   return false;
   }
 }

I have two questions : 我有两个问题:

  1. In what case the input value could be null (x==null) and in what case input value is empty (x == "") ? 在什么情况下,输入值可以为null(x == null),在什么情况下,输入值为空(x ==“”))?

  2. Why is return being used ? 为什么要使用退货? Is it necessary ? 有必要吗 ? Is there a case where we return true ? 是否存在我们返回true的情况?

In what case the input value could be null (x==null) and in what case input value is empty (x == "") ? 在什么情况下,输入值可以为null(x == null),在什么情况下,输入值为空(x ==“”))?

null means the name doesn't have any reference of any object. null表示名称没有任何对象的引用。 where "" means an empty string. 其中""表示空字符串。 in your case you will get null if there is no element. 在您的情况下,如果没有元素,则将为null and "" when its value is empty string. 如果值为空字符串,则为""

Why is return being used ? 为什么要使用退货? Is it necessary ? 有必要吗 ? Is there a case where we return true ? 是否存在我们返回true的情况?

mostly return false is used to to stop the proccessing, if return is false we will no go further 大多数情况下,return false用于停止处理,如果return为false,我们将不做进一步

go to this link for example 例如转到此链接
http://www.codeproject.com/Tips/404274/Client-Side-Validation-using-JavaScript http://www.codeproject.com/Tips/404274/Client-Side-Validation-using-JavaScript

I'd add to @lol answer that the return false; 我会在@lol答案中加上return false; used here is probably used inside some event, like onSubmit for the <form> element in your HTML, this will ensure that the form isn't submitted. 这里使用的可能是在某些事件中使用的,例如HTML中<form>元素的onSubmit ,这将确保不提交表单。 In general return false; 通常return false; will tell the browser not to continue with the default behavior such as submitting a form, or navigating to a page, etc. 会告诉浏览器不要继续默认行为,例如提交表单或导航到页面等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM