validation in javascript - remove the error msg on focus - javascript

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.

Related

Trying to convert this big if else statement into a loop

Hi I'm trying to make this code more clean. I struggle with arrays and loops and have no idea how to convert this into into a loop. This is javascript for a form on an html page and if they leave a field blank, when they hit submit it should return an alert box and if everything is submitted properly it should confirm with them. There's also a reg exp for an acceptable postal code entry.
function validate()
{
var register = document.forms[0];
if (register.fname.value === "")
{
alert("Please fill out your first name.");
return false;
}
else if(register.lname.value === "")
{
alert("Please fill out your last name.");
return false;
}
else if(register.address.value === "")
{
alert("Please fill out your address.");
return false;
}
else if(register.postal.value ==="")
{
alert("Please enter a valid postal code.");
return false;
}
else if(!checkPostal(register.postal.value))
{
alert("Please enter a valid postal code.");
return false;
}
else if(register.eAddress.value === "")
{
alert("Please fill out your email address.");
return false;
}
return confirm("Is the information correct?");
}
//postal code regExp
function checkPostal()
{
var myReg = /^[A-Z]\d[A-Z] ?\d[A-Z]\d$/ig;
return myReg.test(document.getElementById("postal").value);
}
You can make this a pure HTML solution if you want to reduce javascript:
inputs have a required attr ref
additionally, inputs have a pattern attr ref that supports regex.
This kind of solution lets the browser handle feedback
<form>
<label>first name:
<input type="text" name="fname" required
minlength="1">
</label><br/>
<label>last name:
<input type="text" name="lname" required
minlength="1">
</label><br/>
<label>postal code:
<input type="text" name="zip" required pattern="^[A-Z]\d[A-Z] ?\d[A-Z]\d$"
minlength="1">
</label><br/>
<input type="submit" />
</form>
$.each( $( "#input input" ), function( key, element ) {
if( !$(element).val() ) {
$( "#error" + key ).text( "Input " + $( element ).attr( "name" ) + " is required");
return false;
}
});
Set your message as attribute on each element of the form like this:
<form method="POST" action="submit.php">
<input id="item1" type="text" value="" data-message="My error message" data-must="true">
...//do the same for other elements...
</form>
Now loop like below
var elements = document.forms[0].elements;
for (var i = 0, element; element = elements[i++];) {
if (element.getAttribute("must") && element.value === ""){
alert(element.getAttribute("message"));
return false;
}
}
return confirm("Is the information correct?");

jQuery validation is not working in contact form

I want validation through jQuery. I have two fields name and email. email blank field validation is not working.
Here is my code,
<form>
Name : <input type="text" name="name" id="name"><br>
<span id="nameSpan"></span>
<br>
Email:<input type="email" name="email" id="email1"><br>
<span id="emailSpan"></span>
<br>
<input type="submit" id="submitBtn">
</form>
javascript
$(document).ready(function(){
var name = $("#name").val();
var email1 = $("#email1").val();
$("#submitBtn").on("click", function(){
if(name == '')
{
$("#nameSpan").html('Name is required');
return false;
}
else
{
$("#nameSpan").html('');
}
if(email1 == '')
{
$("#emailSpan").html('Email is required');
return false;
}
else
{
$("#emailSpan").html('');
}
});
});
Please guide me where am I wrong. Thanks in advance
You are checking values of inputs only once while page load. We need to check them everytime so lets move this part into onclick function.
$(document).ready(function(){
$("#submitBtn").on("click", function(){
var name = $("#name").val();
var email1 = $("#email1").val();
if(name == '')
{
$("#nameSpan").html('Name is required');
return false;
}
else
{
$("#nameSpan").html('');
}
if(email1 == '')
{
$("#emailSpan").html('Email is required');
return false;
}
else
{
$("#emailSpan").html('');
}
});
});

Javascript form validation needs fix

I'm trying to make a basic form validation but it's not working. I need to make it in such a way that after validation is passed, THEN ONLY it submits the form. I'm not sure how to do it though. My code is below.
[Important request]
** I'm actually pretty new to this so if possible I would like to get some concrete information/explanation concerning the DOM and how to manipulate it and style it (W3School is NOT helping) **
<form id="reg" method="POST" action="user.php" onsubmit="return validate()">
<label for="first">First Name: </label>
<input id="first" name="first" type="text" value="">
<label for="last">Last Name: </label>
<input id="last" name="last" type="text" value="">
<button type="submit">Register</button>
</form>
function validate(){
if(document.getElementById('first').value == ""){
alert('First Name Blank!');
return false;
}else{
return true;
}
if(document.getElementById('last').value == ""){
alert('Last Name Blank!');
return false;
}else{
return true;
}
}
Thanks
Try this:
function validate() {
var validForm = true;
var msg = '';
if (document.getElementById('first').value == "") {
msg += 'First Name Blank! ';
validForm = false;
}
if (document.getElementById('last').value == "") {
msg += 'Last Name Blank! ';
validForm = false;
}
if (!validForm) {
alert(msg);
}
return validForm;
}
Plunker example
Your validation function only validates the first name. Whether it's valid or not, the function returns before checking the last name.
function validate(){
if(document.getElementById('first').value == ""){
alert('First Name Blank!');
return false; // WILL RETURN EITHER HERE ...
}else{
return true; // ... OR HERE
}
The return statement will exit the function at the point it appears, and other code after that is simply not executed at all.
Instead of doing it that way, keep a flag that determines whether the fields are all OK:
function validate(){
var isValid = true; // Assume it is valid
if(document.getElementById('first').value = ""){
alert('First Name Blank!');
isValid = false;
}
if(document.getElementById('last').value == ""){
alert('Last Name Blank!');
isValid = false;
}
return isValid;
}
Here's the code to check for validation and stop it from submitting if it is incorrect data.
<form id="reg" method="POST" action="user.php">
<label for="first">First Name: </label>
<input id="first" name="first" type="text" value="">
<label for="last">Last Name: </label>
<input id="last" name="last" type="text" value="">
<button type="button" id="submit">Register</button>
</form>
document.getElementById('submit').onclick = function(){
if(validate()){
document.getElementById('reg').submit();
}
}
function validate(){
if(document.getElementById('first').value == ""){
alert('First Name Blank!');
return false;
}else if(document.getElementById('last').value == ""){
alert('Last Name Blank!');
return false;
}else{
return true;
}
}
All I have done here is made the submit button a regular button and handled submitting via JS, When an input of type submit is clicked the page will submit the form no matter what. To bypass this you can make it a regular button and make it manually submit the form if certain conditions are met.
Your javascript code can be:
document.getElementById('submit').onclick = function () {
if (validate()) {
document.getElementById('reg').submit();
}
}
function validate() {
if (document.getElementById('first').value == "") {
alert('First Name Blank!');
return false;
} else if (document.getElementById('last').value == "") {
alert('Last Name Blank!');
return false;
} else {
return true;
}
}

Required field validation jquery showing error message

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

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

Categories