Required field validation jquery showing error message - javascript

I validated some fields in my form.. But i have some issues..If without enter fields it shows error message.. If fill out the field still error message is showing..
How to put that ?
My code
$("#Name").focus();
$("#Name").blur(function(){
var name=$('#Name').val();
if(name.length == 0){
$('#Name').after('<div class="red">Name is Required</div>');
}
else {
return true;
}
});
$("#Address").blur(function(){
var address=$('#Address').val();
if(address.length == 0){
$('#Address').after('<div class="red">Address is Required</div>');
return false;
}
else {
return true;
}
});
can anyone help me please?????

You should remove this labels after that user input some data
$("#Name").focus();
$("#Name").blur(function(){
var name=$('#Name').val();
if(name.length == 0){
$('#Name').after('<div class="red">Name is Required</div>');
}
else {
$('#Name').next(".red").remove(); // *** this line have been added ***
return true;
}
});
$("#Address").blur(function(){
var address=$('#Address').val();
if(address.length == 0){
$('#Address').after('<div class="red">Address is Required</div>');
return false;
}
else {
$('#Address').next(".red").remove(); // *** this line have been added ***
return true;
}
});
jsfiddle: DEMO

Your code has bug that it places div as many as time as you blur in empty textbox.
This bug is also removed by my code See-:
Working Demo http://jsfiddle.net/XqXNT/
$(document).ready(function () {
$("#Name").focus();
$("#Name").blur(function () {
var name = $('#Name').val();
if (name.length == 0) {
$('#Name').next('div.red').remove();
$('#Name').after('<div class="red">Name is Required</div>');
} else {
$(this).next('div.red').remove();
return true;
}
});
$("#Address").blur(function () {
var address = $('#Address').val();
if (address.length == 0) {
$('#Address').next('div.red').remove();
$('#Address').after('<div class="red">Address is Required</div>');
return false;
} else {
$('#Address').next('div.red').remove();
return true;
}
});
});
It's better if you use required attribute which does the same work with less code and better manner.
HTML5
<input type="text" name="name" required />
<input type="text" name="address" required />

Try this code (I just changed the structure and added return false) :
$("#Name").focus()
$("#Name, #Address").blur(function(){
if($(this).val().length == 0){
$(this).after('<div class="red">This field is required</div>');
} else {
$(this).next('.red').remove()
}
});
But I think the best way is to add the required attribute to your fields like this :
<input type="text" name="name" required />
<input type="text" name="address" required />

Try to remove the added html in else condition.
if(name.length == 0){
$('#Name').after('<div class="red">Name is Required</div>');
}
else {
$('.red').empty(); //here
return true;
}
And the same for $("#Address")

Related

check all input values of same class is empty jquery

Here I have many input text fields with same class like
<input type="text" class="MyClass"></input>
<input type="text" class="MyClass"></input>
<input type="text" class="MyClass"></input>
My requirement is to check wheather all input fields of this class is empty or not.
I've tried this
if(!('.MyClass').val()){
alert("empty");
}
But it doesn't make any result. Can anyone help?
You can check
$('button').click(function() {
var $nonempty = $('.MyClass').filter(function() {
return this.value != ''
});
if ($nonempty.length == 0) {
alert('empty')
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" class="MyClass" />
<input type="text" class="MyClass" />
<input type="text" class="MyClass" />
<button>test</button>
Or using a flag
$('button').click(function() {
var flag = false;
$('.MyClass').filter(function() {
if (this.value != '') {
flag = true;
//no need to iterate further
return false;
}
});
if (!flag) {
alert('empty')
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" class="MyClass" />
<input type="text" class="MyClass" />
<input type="text" class="MyClass" />
<button>test</button>
You can compare the length of number of input with number of empty input using :
var allemptylength=$(".MyClass").filter(function() {
return this.value.length !== 0;
})});
if($('.MyClass').length== allemptylength.length){
alert("all empty");
}
Working Demo
To make sure each classes are checked, use
$.each($('.MyClass'),function() {
if ($(this).val().length == 0) {
alert('empty');
}
});
You can check it like this:
var isEmpty = !$('.MyClass').filter(function() {
return this.value.trim();
}).length;
Also remove all </input> tags. input elements are self-closable.
try this
var hasNoValue;
$('.MyClass').each(function(i) {
if ($(this).val() == '') {
hasNoValue = true;
}
});
if (hasNoValue) {
alert('All have no value');
}
try is(':checked')
$('.MyClass').each(function(){
alert($(this).is(':checked');)
});
this will alert only the checked elements.
$('input').each(function(index,value){
if($(this).val()!=''){
$(this).addClass('success');
}else{
$(this).removeClass('someClass');
$(this).addClass('warning');
$(this).css('border', '1px solid red');
//do something else...
}
});
Try this . 100% working..
var emptyLength = $(".MyClass").filter(function() {
return this.value == "";
}).length;
if (emptyLength > 0)
{
alert("Please enter all peramerter's value");
return;
}
Thanks.
Try this. It works for me
var flag = 1;
$(".MyClass").each(function(i){
if ($(this).val() == "")
flag++;
});
if (flag == 1)
alert('all have values');
else
alert('some or all doesn\'t have value');

Validate textarea input for alphanumeric value

I want to validate textarea which is an Address field, it must contains both of letters and numbers, at least 1 number .
for example : "Laksda Adisucipto street, no 22A."
but when i just type : "Laksda Adisucipto street" (without number) it can show alert "you must enter at least 1 number"
i'm using Twitter Bootstrap and Validator.js
here's my code
HTML :
<div class="form-group col-md-12">
<label for="address" class="control-label"><span>*</span> <?php echo $this->lang->line('address');?></label>
<textarea class="form-control" id="address" rows="5" required name="address" data-error="Address is required"></textarea>
<span class="help-block with-errors"></span>
</div>
JS :
<script>
$('#address').change(function()
{
var letterNumber = /^[0-9a-zA-Z]+$/;
if(($('#').value.match(letterNumber))
{
return true;
}
else
{
alert("message");
return false;
}
} );
Try this
$('#address').blur(function()
{
var letterNumber = /^[0-9a-zA-Z]+$/;
if(this.value.match(letterNumber))
{
return true;
}
else
{
alert("message");
return false;
}
});
you can check it here: http://jsfiddle.net/oa6eewck/
$('#address').blur(function()
{
var letterNumber = /^[0-9a-zA-Z]+$/;
if(this.value.match(letterNumber))
{
return true;
}
else
{
alert("message");
return false;
}
});
This function will allow only characters and numbers,it will be good for a input text field but since you are having text area "spaces" and "commas" and "periods" are expected right.
So better follow the expression follows :
$('#address').blur(function()
{
var hasNumber = this.value.match(/^[a-zA-Z0-9\s .,]+$/);
if ( hasNumber) {
return true;
} else {
alert("message");
return false;
}
});
$('#address').on('change', function () {
var hasNumber = this.value.match(/\d/);
var isAlfa = this.value.match(/^[0-9a-zA-Z]+$/);
if ( hasNumber && isAlfa ) {
return true;
} else {
alert("message");
return false;
}
});
FIDDLE
adeneo's solution is right. but I think isAlfa should have following value
var isAlfa = this.value.match(/^[A-Za-z\d(-.,) ]+/);

Need alert for all field in javascript

How to get alert for all empty field. In this bellow code, I am able to get alert for username field. how to get alert for all the fields.
JavaScript Code
function null_field(form_name, field_name) {
var field = document.forms[form_name][field_name].value;
if (field == null || field == "") {
alert("All Field Are Required");
return false;
}
}
Login Form
<form action="login_code.php" method="post" onSubmit="return null_field('login_form', 'username')" name="login_form">
<b>Username: </b><input type="text" name="username" class="field">
<b>Password: </b><input type="password" name="password" class="field">
<input type="submit" value="submit">
</form>
Create a function for the whole form instead:
function valid_form(form_name) {
var form = document.forms[form_name],
fields = form.elements, i = 0, l = fields.length;
for (; i < l; i++)
if (fields[i].value === "") {
alert("All Field Are Required");
return false;
}
return true;
}
For each field, you have to call the function. so, for each input tag, call onsubmit="not_null".
I think link will help you what you need. Hope you are looking for same
http://www.c-sharpcorner.com/blogs/8702/validation-summary-in-javascript.aspx
In raw javascript you could do the following:
function null_field(form_name)
{
for(i=0; i<document.forms[form_name].elements.length; i++){
if (document.forms[form_name].elements[i] == null ||document.forms[form_name].elements[i].value == "" || document.forms[form_name].elements.value == undefined)
{
alert("All Field Are Required");
return false;
}
}
return true;
}
If you need one single alert if there are any empty fields, you can use something like this:
function validate_fields(form_name) {
var has_empty_fields = false;
for (var field in document.forms[form_name].elements) {
if(field == null || field.value == "") {
has_empty_fields = true;
break;
}
}
if (has_empty_fields) {
alert("All Fields Are Required");
return false;
}
return true;
}

Textarea Empty check

HTML
<form name="myForm" id="myForm" onsubmit="return validate();" action="<?php echo $_SERVER['PHP_SELF']?>">
<input type="text" name="name" id="name">
<textarea name="details" id="details"></textarea>
<input type="submit">
</form>
Javascript
function validate()
{
if(document.getElementById('details').value == '')
{
alert("Please Provide Details!");
document.getElementById('details').focus();
return false;
}
else if(document.getElementById('name').value == '')
{
alert("Please Provide Name!");
document.getElementById('name').focus();
return false;
}
else
return true;
}
OR
function validate()
{
if(document.myForm.details.value == '')
{
alert("Please Provide Details!");
document.myForm.details.focus();
return false;
}
else if(document.myForm.name.value == '')
{
alert("Please Provide Name!");
document.myForm.name.focus();
return false;
}
else
return true;
}
I have seen the codes from previous Stack Overflow but as I am using these and it is not working. Will anyone help to solve check empty Value on Textarea using Javascript but not jquery.
The Reference I have used
how to check the textarea content is blank using javascript?
And
How to check if a Textarea is empty in Javascript or Jquery?
I think you may have space problem on your textarea. Use a trim function to reduce that. Here is the example following. I hope it may solve your problem.
JavaScript Add this function
function trimfield(str)
{
return str.replace(/^\s+|\s+$/g,'');
}
And your JavaScript function
function validate()
{
var obj1 = document.getElementById('details');
var obj2 = document.getElementById('name');
if(trimfield(obj1.value) == '')
{
alert("Please Provide Details!");
obj1.focus();
return false;
}
else if(trimfield(obj2.value) == '')
{
alert("Please Provide Name!");
obj2.focus();
return false;
}
else
return true;
}
OR
function validate()
{
var obj1 = document.myForm.details;
var obj2 = document.myForm.name;
if(trimfield(obj1.value) == '')
{
alert("Please Provide Details!");
obj1.focus();
return false;
}
else if(trimfield(obj2.value) == '')
{
alert("Please Provide Name!");
obj2.focus();
return false;
}
else
return true;
}
And HTML with PHP
<form name="myForm" id="myForm" onsubmit="return validate();" action="<?php echo $_SERVER['PHP_SELF']?>">
<input type="text" name="name" id="name">
<textarea name="details" id="details"></textarea>
<input type="submit">
</form>
You can use following jQuery to escape white spaces.
if($("#YourTextAreaID").val().trim().length < 1)
{
alert("Please Enter Text...");
return;
}

validation in javascript - remove the error msg on focus

i'm not very well-versed with javascript, so please bear with me.
i've a form in which i validate the controls with javascript. the error is displayed when the fields are empty via a div, but when i focus and type something in the textbox, the div should go away. but the error div doesn't and even if i type something valid, it still displays the div.
i'd like to know where am i going wrong with this script:
<script type="text/javascript">
var err = document.getElementById("errmsg");
function checkInput(inPut) {
if (inPut.getValue() == "") {
err.setStyle('display', 'block');
err.setTextValue("Field cannot be empty!");
inPut.focus();
return false;
}
else {
return true;
}
}
function checkTextBox(textBox)
{
if (textBox.getValue() == "") {
err.setStyle('display', 'block');
err.setTextValue("Field cannot be empty!");
textBox.focus();
return false;
}
else if (!checkValidity(textBox.getValue())) {
err.setStyle('display', 'block');
err.setTextValue("Please enter a valid email address!");
textBox.focus();
return false;
}
else {
return true;
}
}
. . .
<div id="errmsg" class="invalid" style="display:none;"></div> <br />
. . .
<input type="text" tabindex="1" name="name" id="name" class="input_contact" onblur="checkInput(this);"/> <br />
. . .
<input type="text" tabindex="2" name="email" id="email" class="input_contact" onblur="checkTextBox(this);"/> <br />
it's a form in facebook app but while the fbjs works, i assume there's a problem with my basic javascript.
try this
var err = document.getElementById("errmsg");
function checkInput(inPut) {
if (inPut.getValue() == "") {
err.setStyle('display', 'block');
err.setTextValue("Field cannot be empty!");
inPut.focus();
return false;
}
else {
err.setStyle('display', 'none');
err.setTextValue("");
return true;
}
}
function checkTextBox(textBox)
{
if (textBox.getValue() == "") {
err.setStyle('display', 'block');
err.setTextValue("Field cannot be empty!");
textBox.focus();
return false;
}
else if (!checkValidity(textBox.getValue())) {
err.setStyle('display', 'block');
err.setTextValue("Please enter a valid email address!");
textBox.focus();
return false;
}
else {
err.setStyle('display', 'none');
err.setTextValue("");
return true;
}
}
To get the div to disappear when you first type something, instead of when the field is checked, you'll also need onchange and/or onfocus event handlers for the fields:
<input type="text" tabindex="1" name="name" id="name" class="input_contact"
onblur="checkInput(this);"
onfocus="err.setStyle('display', 'none');"
onchange="err.setStyle('display', 'none');"
/>
They could also be set inside checkInput(), if you so desire.

Categories