Ankit
Ankit

Reputation: 4644

Javascript Validation for required fields

I am learning javascript and in a form validation example I found this : To check for required field

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 == "") ?

  2. Why is return being used ? Is it necessary ? Is there a case where we return true ?

Upvotes: 1

Views: 125

Answers (2)

Govind Singh
Govind Singh

Reputation: 15490

In what case the input value could be null (x==null) and in what case input value is empty (x == "") ?

null means the name doesn't have any reference of any object. where "" means an empty string. in your case you will get null if there is no element. and "" when its value is empty string.

Why is return being used ? Is it necessary ? Is there a case where we return true ?

mostly return false is used to to stop the proccessing, if return is false we will no go further

go to this link for example
http://www.codeproject.com/Tips/404274/Client-Side-Validation-using-JavaScript

Upvotes: 2

mpcabd
mpcabd

Reputation: 1807

I'd add to @lol answer that the 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. In general return false; will tell the browser not to continue with the default behavior such as submitting a form, or navigating to a page, etc.

Upvotes: 2

Related Questions