Using javascript we can validate the data before sending to server. In this tutorial i’ll show you how to validate empty field in javascript. To demostrate this let’s first create one form.
Javascript Objective Interview Questions
1 2 3 4 5 |
<form name="validate_form"> <textarea id="text_val" cols="50"> </textarea> <input onclick="return validate_empty_field()" type="submit" value="submit" /> </form> |
I have created one form in which there is one textarea and submit button. When user click on submit button, first we check whether user has input any value in textarea. If the value of textarea is empty we alert message and return false otherwise form will be submitted successfully.
How to Validate Empty Field in Javascript
When user click on submit, on the click of submit we call validate_empty_field() function, let’s define this function.
1 2 3 4 5 6 7 8 9 10 11 12 |
function validate_empty_field(){ var fieldValue = document.getElementById('text_val').value; if(fieldValue==null || fieldValue==" "){ alert("Please enter some text"); return false; } return true; } |
Similarly you can field any input field using javascript.