7

I have a jsp page with some TextBoxes. Now I want to fill them with some information and click the submit button. But I need to check whether this TextBox is empty or not.

How can I do this?

numaroth
  • 1,295
  • 4
  • 25
  • 36
user222585
  • 171
  • 2
  • 4
  • 9

7 Answers7

15

Using regexp: \S will match non whitespace character:anything but not a space, tab or new line. If your string has a single character which is not a space, tab or new line, then it's not empty. Therefore you just need to search for one character: \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;
    }
}

HTML:

<form onsubmit="return checkvalue(this)">
    <input name="myString" type="text" value='' id="myString">
    <input type="submit" value="check value" />
</form>
Pieter VDE
  • 2,195
  • 4
  • 25
  • 44
sweets-BlingBling
  • 4,432
  • 2
  • 17
  • 14
  • +1 that prevented from redirecting to another page and solvd my problem..cheers.. – Lucky Feb 18 '13 at 13:07
  • @dreamonic - here you indented code that needed it, but in my opinion did not go far enough. The function and if's content are left aligned - no need to indent the code under the script tag and waste 12 spaces – mplungjan Jun 06 '13 at 07:52
  • @mplungjan That's a matter of opinion. I should have indented the JavaScript function though -- like the last edit I've committed. – Pieter VDE Jun 06 '13 at 08:22
7

Canonical without using frameworks with added trim prototype for older browsers

<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>

Here is the inline version, although not recommended I show it here in case you need to add validation without being able to refactor the code

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
}

passing the form object in (this)

<form onsubmit="return validate(this)">
  <input type="text" name="textField1" value="" /><br/>
  <input type="submit" />
</form>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 1
    @Dreamonic I fail to see why you would indent my code so far it cannot be read without scrolling. I indented it the way I prefer to indent it, for maximum visibility and still indented. – mplungjan Jun 05 '13 at 16:40
  • 1
    Couldn't resist, could you? :) Well, since we're gonna do this now, I'll just leave this here: http://meta.stackexchange.com/questions/183169 – Robert Harvey Jun 05 '13 at 16:55
  • No problem. Perhaps he will read it - too bad it cost me 10 meta rep – mplungjan Jun 05 '13 at 16:58
  • Even now, not all of your code can be read without scrolling. I genuinely don't think there's anything wrong with trying to upgrade readability and code clarification. – Pieter VDE Jun 06 '13 at 07:12
  • Actually, the code you cannot read is a paste only piece of trim. The window.onload code and the comments to the right were the ones I was annoyed about - Just please leave my code alone and if you must, indent code that needs it. – mplungjan Jun 06 '13 at 07:49
  • If you'd indent your code properly I wouldn't have edited it. Now, all your main tags (e.g. html, head, script, body) are on one line. What you can also do, is omit these tags, and just separate your code into 2 blocks: one containing the JavaScript, and one containing the HTML. Anyways, if it's such a bother to you, I'll leave your posts alone. – Pieter VDE Jun 06 '13 at 08:27
  • As i said - your opinion of "properly" and mine differs. I strongly suggest you do not "fix" indentation unless there is none. I have the html there when the user is a noob to show where the script goes. Thanks – mplungjan Jun 06 '13 at 09:44
5

Using this JavaScript will help you a lot. Some explanations are given within the code.

<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>
gniourf_gniourf
  • 44,650
  • 9
  • 93
  • 104
Rubyist
  • 6,486
  • 10
  • 51
  • 86
  • 1) Not all browsers will understand text_form - you should use document.text_form 2) pass the form to the function is far safer and simpler 3) what's with the "DUDE" ? Could be a DUDETTE – mplungjan Aug 18 '10 at 06:12
2

You can also check it using jQuery.. It's quite easy:

<html>
    <head>
        <title>jQuery: Check if Textbox is empty</title>
        <script type="text/javascript" src="js/jquery_1.7.1_min.js"></script>
    </head>
    <body>
        <form name="form1" method="post" action="">
            <label for="city">City:</label>
            <input type="text" name="city" id="city">
        </form>
        <button id="check">Check</button>
        <script type="text/javascript">
             $('#check').click(function () {
                 if ($('#city').val() == '') {
                     alert('Empty!!!');
                 } else {
                     alert('Contains: ' + $('#city').val());
                 }
             });                
        </script>
    </body>
</html>
Pieter VDE
  • 2,195
  • 4
  • 25
  • 44
Muhammad Azeem
  • 479
  • 1
  • 5
  • 20
0

Whatever method you choose is not freeing you from performing the same validation on at the back end.

Alex
  • 210
  • 2
  • 13
0

The most simple way to do it without using javascript is using required=""

<input type="text" ID="txtName"  Width="165px" required=""/>
PRATEEK GHOSH
  • 243
  • 1
  • 15
-1
<pre><form name="myform"  method="post" enctype="multipart/form-data">
    <input type="text"   id="name"   name="name" /> 
<input type="submit"/>
</form></pre>

<script language="JavaScript" type="text/javascript">
 var frmvalidator  = new Validator("myform");
    frmvalidator.EnableFocusOnError(false); 
    frmvalidator.EnableMsgsTogether(); 
    frmvalidator.addValidation("name","req","Plese Enter Name"); 

</script>

Note: before using the code above you have to add the gen_validatorv31.js file.

Mr. Xcoder
  • 4,719
  • 5
  • 26
  • 44