Tuesday, 21 March 2017

c# Dictionary Part3 (Refactoring if else condtion)

12:16 Posted by Nikesh No comments

In this post we will cover refactoring of nested if else in large sensitive codes. Large sensitive here means when we have a code where only conditioned data present of static key ids in large if else file.

To fix this we can again use dictionary as a good part of key value pair of organizing data.

For example suppose we have to work with multiple static id value whose condition has different quantity as whole sellers:

Suppose we have view written like this......
  if(id== 1)
  {
  //calculation for id one
<input type=number" min="10" />
  }
 else if(id == 2)
  {
   //calculation for id two
<input type=number" min="12" />
  }
  else if(id==3)
   {
  //calculation for id three
<input type=number" min="15" />
  }

and so on we have multi nested conditions. how we can refactor those so we can make our code readability better.

Let's see how we can do that.

To get better readability we can create a dictionary function which can return dictionary of lists values

public static Dictionary<string, List<string>> GetMyQuantityInfo()
{

 Create your type of list available based on your conditions.

List<string> pTypeForMin10Quantity = new List<string>() {" id of all products whose quantity need 10" };
List<string> pTypeForMin12Quantity = new List<string>() { "id of all products whose quantity need 12" };
List<string> pTypeForMin50Quantity = new List<string>() {"id of all products whose quantity need 15 "};

// Bind lists to dictionary with some keys as i am using chkfor10,12 and 15 so on

Dictionary<string, List<string>> QuanityInfo = new Dictionary<string, List<string>>();
QuanityInfo.Add("chkfor10", pTypeForMin10Quantity);
QuanityInfo.Add("chkfor12", pTypeForMin12Quantity);
QuanityInfo.Add("chkfor15", pTypeForMin15Quantity);


return QuanityInfo;

}


Now Create another dictionary which says which type of check we have to do



public static Dictionary<string, int> allquantityiformation()

{

Dictionary<string, int> alltypproduct = new Dictionary<string, int>();
alltypproduct.Add("chkfor10", 10);
alltypproduct.Add("chkfor12", 12);
alltypproduct.Add("chkfor15", 15);


return alltypproduct;

}



Now calling, how we can get those conditons:


List<string> ProductIdAndTypesforMinQuantity = new List<string>() {};


var QuantityInfo = Model.GetMyQuantityInfo();

var aqi = Model.allquantityiformation();

//Now pass your type of productid in QuantityInfo.ContainsKey() so we can check what type of quantity information available for my products.

// here i am doing foreach because i have to check based on type of quantity check
//This foreach will go to my type allquantityiformation dictionary and check product in this type of dictionary

//here our ptype will be chkfor10,chkfor12,chkfor15


foreach (string ptype in allquantityifo)

{
if (QuantityInfo.ContainsKey(ptype))
{
//Now get its all list of id in an empty list

//Based on check in each loop get its respective list from dictonary QuantityInfo

ProductIdAndTypesforMinQuantity = QuantityInfo[ptype];

string id = Id; -- Remember this will be our id of our product which we current checking in list for availability, we can get id from product datatable rows. ex: string id = dr["ProductId"].ToString();


if (ProductIdAndTypesforMinQuantity.Contains(id))
{
             //Getting minimum value for chktype currently going

Int64 MinValue = aqi[ptype]; --- this will give us 10 or 12 or 15
   // Binding minimum value current available to input control and set an boolean value  minSetupdon       true
<input value='@dr["Quantity"]' type="number" min="@MinValue" maxlength="2" >
minSetupdone = true;
}
else
{
availabeMin = false;
}

}
else
{
ProductIdAndTypesforMinQuantity = new List<String>() { };

}
}

//Now when avaibility not found set min value 0

if (availabeMin == false && minSetupdone == false)
{
<input value='@dr["Quantity"]' type="number" min="0">
}

In that way we can refactor our large size nested if else conditions easily and makes them more readable.



Wednesday, 8 February 2017

C# Dictionary Part2




In this post we will cover simple steps to get
 table data from Sql query And bind data to select element Using Jquery And MVC using dictionary and without using models.

To do this we can use  ajax which will get table data from sql table and bind to select and


create a dictionary in c# which use object parameters to bind dynamic data.


We will get our data to datatable and pass to an dictionary creator function.



   public JsonResult GetTableDataInJsonFormat(Int64 id=0)
    {
       try
       {
        DataTable dt = GetAllColumns(Convert.ToInt64(PrimaryKey.ToString()));

       ViewBag.AllColumns = GetColumnsInDictionaryFormat(dt);


       return Json(new { success = true, msg = "", AllColumns = Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.
AllColumns)}, JsonRequestBehavior.AllowGet);
            }
            catch(Exception ex)
            {
                return Json(new { success = false, msg = "Error: " + ex.Message.ToString(), AllColumns = "" }, JsonRequestBehavior.AllowGet);
            }          
        }





  static public Dictionary<String, Object> GetColumnsInDictionaryFormat(DataTable dt)
     {
       Dictionary<String, Object> Columns = new Dictionary<String, Object>();
       List<Dictionary<String, Object>> rows = new List<Dictionary<String, Object>>();
            try
            {
                foreach (System.Data.DataRow dr in dt.Rows)
                {
                Dictionary<String, Object> row = new Dictionary<string, object>();
                row.Add("Id", dr["Id"].ToString());
                row.Add("ColumnOneDynamicName", dr["ColumnOne"].ToString());
                row.Add("ColumnTwoDynamicName", dr["ColumnTwo"].ToString());
                  
                    rows.Add(row);
                }
                Columns.Add("rows", rows);
            }
            catch {}
            return Columns;
        }





This will convert our datatable to dictionary format to use in ajax or to process dictionary.


Now we can use it in view as below and bind to select.



        function addColumns() {
          var selectData = $('#dropdownId').find(':selected').val();

         


            $.ajax({

                type: "GET",
                url: '/GetTableDataInJsonFormat/' + selectData,
                data: '',
                success: function (data) {
                    if (data.success) {

                        data = jQuery.parseJSON(data.AllColumns);

                        var str = '';
                        $.each(data['rows'], function (key, element) {
                            var tmpColumn = element["ColorCode"].toLowerCase() == "#ffffff" ? "black" : "white";

                 if (element["ColumnOneDynamicName"].toLowerCase() == "matchcase") {

                                str += "<option value='" + element['Id'] + "'  selected='selected'>" + element['ColumnOneDynamicName'] + "</option>";
                            } else {
                                str += "<option  value='" + element['Id'] + "' >" + element['ColumnOneDynamicName'] + "</option>";
                            }

                        });

                        $('#dropdownId').html(str);
                    } else {
                        $('#dropdownId').html('');
                    }
                }
            });
        }




Wednesday, 18 January 2017

Print DataTable To CSV in MVC C#


Code to print simple data table values to csv.



public ActionResult PrintDataToCsv()
        {

            string StartDate = Request.Params["StartDateP"] == null ? "" : Request.Params["StartDateP"].ToString();
            string EndDate = Request.Params["EndDateP"] == null ? "" : Request.Params["EndDateP"].ToString();

            string PageName = Request.Params["PageName"] == null ? "" : Request.Params["PageName"].ToString();

            String EnddateConverted = "";
            String StardateConverted = "";
            if (StartDate != "")
            {
                StardateConverted = Convert.ToDateTime(StartDate.ToString()).ToString("MM/dd/yyyy");
            }
            else
            {
                StardateConverted = StartDate;
            }
            if (EndDate != "")
            {
                EnddateConverted = Convert.ToDateTime(EndDate.ToString()).ToString("MM/dd/yyyy");
            }
            else
            {
                EnddateConverted = EndDate;
            }
       
            System.Web.UI.WebControls.GridView gv = new System.Web.UI.WebControls.GridView();

//Here is my datatable which return from procedures.

            DataTable dt = GetAllDataToPintToCsv(StardateConverted, EnddateConverted,PageName);

            StringWriter sw = new StringWriter();
           //Header Part
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                sw.Write(dt.Columns[i]);
                if (i < dt.Columns.Count - 1)
                {
                    sw.Write(",");
                }
            }
            sw.Write(sw.NewLine);

//Header Data

            foreach (DataRow dr in dt.Rows)
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    if (!Convert.IsDBNull(dr[i]))
                    {
                        string value = dr[i].ToString();
                        if (value.Contains(','))
                        {
                            value = String.Format("\"{0}\"", value);
                            sw.Write(value);
                        }
                        else
                        {
                            sw.Write(dr[i].ToString());
                        }
                    }
                    if (i < dt.Columns.Count - 1)
                    {
                        sw.Write(",");
                    }
                }
                sw.Write(sw.NewLine);
            }
            sw.Close();

         

            gv.DataBind();
            Response.ClearContent();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment; filename=myfilename.csv");
            Response.ContentType = "text/csv";
            Response.Charset = "";

            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();


            return RedirectToAction("/account/PrintDataToCsv");

        }




   <form name="Printing" id="Printing" action="/account/PrintDataToCsv" >

              <input type="hidden" id="StartDate" name="StartDateP"  value="@StartDate">
               <input type="hidden" id="EndDate" name="EndDateP" value="@EndDate">
              <input type="hidden" name="PageName" id="searchdata"  value="@PageName" />
           
              <button type="submit" class="btn btn-success  btn-export" title="Print">Export</button>
     </form>

Javascript Design Pattern



Hi, Today we will learn to write a very basic modular pattern of JavaScript. But before going ahead we should first familiar with what design pattern actually do.
Design pattern represents that code is written by experienced object oriented software developers.
So as we write daily multiple codes, and if we did not organised our code then day by day it goes complex. We can prevent from being a irritated developers by organizing our code.

We are going to learn a very basic of modular pattern that is commonly used by experience developers.

Suppose we have to do multiple calculation and for this we have to write too many functions and if we organized it in patterns it become readable. Here my calculation function will store all calculation functions and based on its default calling on calculation function load.

Syntax:-       var myFunction = function(){
                                    var fun1 = function(){}
                                     var fun2 = function(){}
                      return{ one: fun1,two:fun2}
                    };



var MyCalculation = function () {

//Here we can define our private variable that we can access in functions.

var addOperation = function (a, b) {
        alert(a + b);
    };
var subtrOperation = function (a, b) {
        alert(a - b);
    }


return {

 //Here you can define public accessibility for this Complete function.  
//Note in our whole function this is only entry and exist which will returned.

        add: addOperation ,
        subtract: subtrOperation ,
        multiple: function (a, b) {
            alert(a * b);
        }
    }
};

Now calling part 

//For using our modular function we first need to create an instance for our function.

var calculation = new MyCalculation ();
calculation .add(1, 2);
calculation .subtract(5, 1);
calculation .multiple(2, 4);

simple.....



Now i am going to explain another function which we can use to enhance our programming experience in javascript. Below given app i have studied from google and just want to clear how to program such apps.

As for beginner, it wouldn't be easy to understand so for faster to study i am writing points as numbers 1,2,3,4 you can go with these steps, so that it become easier to study.
In my case i will point function caller as point 1.





 
var myWebApp = (function() {
    "use strict"
 
 
 
 var myDiv= $("#myDiv"); // Getting Div Id  
 
    // private variables  
    var privateMessageVal;
    var privateAdditionalMessageVal;
   
   //Create an object which will hold our messages.

    var messageCtrls = {};
 
    var myconfigfile = {

        mySelector: null, // $("#myDiv")
        messageSelector: null, // $(".message")
        additionalMessageSelector: null, // $(".additional_message")
        options: {
            showOK: true,
            showCancel: true,
            warningLevel: 1,
        }
    }
 
writing ajax call functions for all events as a dynamic, in which we can pass parameter and result will be bind to messageCtrls object.


    // AJAX calls
    var getResult = function(msgs) {   ---------------------------------  (Point 8)
        $.ajax({
            url: '/urlOfAction',
            type: 'POST',
            dataType: "json",
            data: {'message' : msgs},
            success: function(data) {
                // ...
                messageCtrls.mainMessageDiv.html(data.result);
             
               //Here i am binding default controls for any dom to messageCtrls.

                messageCtrls = bindMessageControls();
                },
            error: function() {
                // ...
                }
        });
    };
 
    var inputClick = function(event) {   ---------------------------------  (Point 7)
        event.preventDefault();
        // depending on if you'll reuse these selectors throughout
        // the app I might have these as variables

        $('.loading').html('<img class="remove_loading" src="/graphics/loading.gif" alt="" />');
 
        // try to avoid these
        var msgs = $(".additionalMessage").val();
        // and use this
        var msgs = myconfigfile.additionalMessageSelector.val();
        // or
        var msgs = privateAdditionalMessageVal;
 
        if (msgs == ""){
            $("#msgs_empty").notification();   ////validating field if it is empty. and if not then call to ajax.
            $('.remove_loading').remove();
        } else {
            getResult(msgs);
        }
    };
 
//Here we will write all default controls needed for our App.

    var bindMsgControls = function () {
        var self = {};
 
        // Modal
        self.thisModal = $(".MessageModal");
 
        // CheckBoxs
        self.fooCb = $(".foo_checkbox");
       
        // Buttons
        self.okBtn = $(".btnOk");   ---------------------------------  (Point 6)
        self.cancelBtn = $(".btnCancel");
 
        // Divs
        self.mainMessageDiv = $(".main_message");   ---------------------------------  (Point 9)
        self.additionalMessageDiv = $(".addtional_message");
 
        //Help Icons
        self.HelpIcon = $(".help-icon");
 
        return self;
    };
 
    var bindVals = function () {
        //check to make sure we have a valid config passed in before we set the values
        if (!myconfigfile.messageSelector) throw "Invalid configuration object passed in init()";
       
        //bind the values to "private variables"
        pvtMessageVal = myconfigfile.messageSelector.val();
       
        //this control is optional, test existence
        if(config.additionalMessageSelector.length)
            pvtAdditionalMessageVal = myconfigfile.additionalMessageSelector.val();
    };
 
    var bindAllFunctions = function() {   ---------------------------------  (Point 4)
     
//This function will bind function to controls that are taken in bindMsgControls
//We can directly take our controls and bind function to them or we can call to object's controls, here messageCtrls's okBtn that is called by bindMsgControls, here we can get them and call function on its events.

        $("btnOk").on("click", inputClick)
     
//We can use as above but we have controls's object so we will write

        messageCtrls.okBtn.on('click, inputClick')   ---------------------------------  (Point 5)
    };
 
// On Init Call We need to bind controls and their functions first.

    var init = function () {   ---------------------------------  (Point 3)
        messageCtrls = bindMsgControls();
        bindAllFunctions();
    };
 
    var showMessage = function (cfg) {
        myconfigfile = cfg;
        bindVals();
        messageCtrls.thisModal.modal({
            show: true,
            keyboard: false,
            backdrop: "static"
        });
    };
   
    return {
        init: init,   ---------------------------------  (Point 2)
        show: showMessage,
        getMessage: getResult
        //anything else you want available
        //through myMessageApp.function()
        //or expose variables here too
    };
 
})();
 


//Usage

//A call to our above app init function

(Point 1)
--------------

$("document").ready(function () {
    myMessageApp.init();
});

So in totally we need to take care of 8 to 9 points which can clear our view. Here only our init of myapp will bind all controls and its functions, events, errors and pass it to its respective div.

That's way we can make our code look like self app. You can write in various ways but this technique will definitely perfect for modular pattern.




Tuesday, 17 January 2017

Jquery Validation

12:06 Posted by Nikesh No comments

Hi, Today we practice on validation from beginner to advanced.

First we will grab js file required files jquery.js and jquery.validate.min.js

Jquery has validate function where we can write rule for our controls and gives properties to validate and in case if it not validate we can write error messages.

lets create a basic validation code in jquery.

      <form name="validationform" id="validationform" action="thankspage.html" method="post">

Name: <input type="text" name="name" class="form-control">  <br/>
Email: <input type="email" name="email" class="form-control"/>  <br/>

<input type="submit" value="Submit" name="submit" />

</form>


<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>


<script>
$(document).ready(function(){

console.log('My Validation Start..');

$("#validationform").validate({
            rules: {                      //-----------------------Writing Rule in rules{} object.
  name: {      //----------------------Writing Conditions for controls.
required: true,
minlength: 2,
                               maxlength: 50
             },
                          email: {
                                 required: true,
                                 email: true
                                     }
                    },
            messages: {             //----------Writing messages for each conditions written above.
                            name: {
required: "Name is required gmgu",
minlength: "Minimum 2 required",
maxlength: "maximum 50"
         },
                             email: {
                                        required: "Email required",
                                         email: "Invalid Email-id"
                                    }
                            }
               });


});
</script>



In last we should apply some css 


<style type="text/css">

input.valid
    {
        border: solid 1px #00FF00;
    }

    input.error
    {
         border: solid 1px #FF0000;
    }
   
    label.error
{
color: #FF0000;
display: none;
font-size: 18px;
min-width: 150px;
text-align: left;
z-index: 4;
}
</style>





Now lets jump more ahead. Every day we write many javascript codes and got too many plugins js which some times become messy or get complex so we will go one more step ahead where we will write simple code which don't have connection with plugins and we can use only with jquery itself.

So for this we will validate a form field also we will go with asp.net page because also i am from this background you can also go with above html and it will work with data-vald attributes

So let's get started..

First i will go with asp.net write a form where you have controls:



@Html.TextBoxFor(m => m.Name, new { @name = "ContatName",data_vald = "N", @id = "Name", @class = "form-control", @maxlength = "250", @placeholder = "Enter Name" })
@Html.ValidationMessageFor(m => m.Name)



@Html.TextBoxFor(m => m.SchoolOrganization, new { @name = "SchoolOrganization", data_vald = "S", @id = "SchoolOrganization", @class = "form-control", @maxlength = "250", @placeholder = "School/Organization" })
 @Html.ValidationMessageFor(m => m.SchoolOrganization)
                                             
@Html.TextBoxFor(m => m.PhoneNumber, new { @name = "PhoneNumber", data_vald = "P", @class = "form-control", @id = "PhoneNumber", @maxlength = "15", @placeholder = "Enter Phone Number" })
@Html.ValidationMessageFor(m => m.PhoneNumber)

@Html.TextBoxFor(m => m.EmailId, new { @name = "EmailId", data_vald = "E", @id = "EmailId", @class = "form-control", @maxlength = "50", @placeholder = "Enter E-mail Id" })
@Html.ValidationMessageFor(m => m.EmailId)



Note:-  I am using data_vald for data-vald attribute of  html and giving his respective names.



Then we will write jquery functions as below



<script type="text/javascipt">

 $(function () {

/////////////On every controls change event writing a function which will check if no any input found in control and if no any validation error exist on page then add error message and customize its borders.
             
                $('#Name').change(function () {
                    if (!$('#Name').val()) {
                        if ($("#Name").next(".field-validation-error").length == 0) // only add if not added
                        {
                            $('#Name').css('border', '1px solid #AC004A');
                            $("#Name").after("<div class='field-validation-error' style='color:#AC004A;margin-bottom: 20px;'>Name is required*</div>");
                            //$('#Name').focus();
                            //return;
                        }
                    } else {
                        $("#Name").next(".field-validation-error").remove(); // remove it
                        $('#Name').css('border', '1px solid black');
                    }
                });


                $('#PhoneNumber').change(function () {
                    if (!$('#PhoneNumber').val()) {
                      
                 if ($("#PhoneNumber").next(".field-validation-error").length == 0) // only add if not added
                        {
                            $('#PhoneNumber').css('border', '1px solid #AC004A');
                            $("#PhoneNumber").after("<div class='field-validation-error' style='color:#AC004A;margin-bottom: 20px;'>Please Enter Phone*</div>");
                          //  $('#PhoneNumber').focus();
                          //  return;
                        }
                    } else {
                        $("#PhoneNumber").next(".field-validation-error").remove(); // remove it
                        $('#PhoneNumber').css('border', '1px solid black');
                    }
                });
                $('#EmailId').change(function () {
                    debugger;

                    $("#EmailId").next(".field-validation-error").remove(); // remove it
                    $('#EmailId').css('border', '1px solid black');

                    if (!$('#EmailId').val()) {
                        if ($("#EmailId").next(".field-validation-error").length == 0) // only add if not added
                        {

                            $('#EmailId').css('border', '1px solid #AC004A');
                          //  $("#EmailId").after("<div class='validation' style='color:#AC004A;margin-bottom: 20px;'>Email address is required*</div>");
                         //   $('#EmailId').focus();
                          //  return;
                        }
                    } else {

                        if (validateEmail($('#EmailId').val())) {
                           // $("#EmailId").next(".field-validation-error").remove(); // remove it
                            $('#EmailId').css('border', '1px solid black');
                        }
                        else {
                            $('#EmailId').css('border', '1px solid #AC004A');
                            // $("#EmailId").after("<div class='validation' style='color:#AC004A;margin-bottom: 20px;'>Email address is required*</div>");
                        }

                     
                    }
                });

                $('#SchoolOrganization').change(function () {
                  

                    $("#SchoolOrganization").next(".validation").remove(); // remove it
                    $('#SchoolOrganization').css('border', '1px solid black');

                    if (!$('#SchoolOrganization').val()) {
                        if ($("#SchoolOrganization").next(".SchoolOrganization").length == 0) // only add if not added
                        {
                            $('#SchoolOrganization').css('border', '1px solid #AC004A');
                            //  $("#EmailId").after("<div class='validation' style='color:#AC004A;margin-bottom: 20px;'>Email address is required*</div>");
                            //   $('#EmailId').focus();
                            //  return;
                        }
                    } else {

                        if (validateEmail($('#SchoolOrganization').val())) {
                            $("#SchoolOrganization").next(".validation").remove(); // remove it
                            $('#SchoolOrganization').css('border', '1px solid black');
                        }
                        else {
                            $('#SchoolOrganization').css('border', '1px solid #AC004A');

                        }


                    }
                });




////After completing  each we will write validation function which can occur after form submit.


 function checkMandatoryFields(e) {
               
//// For this i am going to create an array which can store my data-vald attributes in array and from there i can loop and check which field was not valid values.

                          
                var validationcontent = [];

/////////////Emptying array before adding values.//////////////////
                for (var i = validationcontent.length; i > 0; i--) {

                    validationcontent.pop();

                }
Check for each controls validity and in case of not valid push that too validationcontent array.
So we can check their data-vald values and based on that update messages.


Checking each controls validity separately 


                if (!$('#BillingName').val()) {
                    validationcontent.push($('#BillingName').attr('data-vald'))
                }
                if (!$('#PhoneNumber').val()) {
                    validationcontent.push($('#PhoneNumber').attr('data-vald'))
                } if (!$('#EmailId').val()) {
                    validationcontent.push($('#EmailId').attr('data-vald'))
                } if (!$('#SchoolOrganization').val()) {
                    validationcontent.push($('#SchoolOrganization').attr('data-vald'))
                }

Loop through validationcontent and based on their values show messages for them

                for (var i = 0, len = validationcontent.length; i < len; i++) {
                    var s = validationcontent[i];
                    if (s == 'N') {
                   if ($("#Name").next(".field-validation-error").length == 0) // only add if not added
                        {
                            $('#Name').css('border', '1px solid #AC004A');
                            $("#Name").after("<div class='field-validation-error' style='color:#AC004A;margin-bottom: 20px;'>Name is required*</div>");
                           
                         
                        }
                        else {
                           $("#BillingName").next(".field-validation-error").remove(); // remove it
                            $('#BillingName').css('border', '1px solid black');

                        }
                    }
                    if (s == 'S') {
                        if ($("#SchoolOrganization").next(".validation").length == 0) // only add if not added
                                {
                                    $('#SchoolOrganization').css('border', '1px solid #AC004A');                                   
                                    $("#SchoolOrganization").after("<div class='validation' style='color:#AC004A;margin-bottom: 20px;'>School/Organization Name is required*</div>");
                                 
                                }
                            else {
                               $("#SchoolOrganization").next(".validation").remove(); // remove it
                                $('#SchoolOrganization').css('border', '1px solid black');
                            }
                    }
                    if (s == 'P') {
                        if ($("#PhoneNumber").next(".field-validation-error").length == 0) // only add if not added
                                {
                                    $('#PhoneNumber').css('border', '1px solid #AC004A');
                                    $("#PhoneNumber").after("<div class='field-validation-error' style='color:#AC004A;margin-bottom: 20px;'>Please Enter Phone*</div>");
                                  
                          
                        }
                        else {
                               $("#PhoneNumber").next(".field-validation-error").remove(); // remove it
                                $('#PhoneNumber').css('border', '1px solid black');
                           }
                    }
                    if (s == 'E') {
                        if ($("#EmailId").next(".field-validation-error").length == 0) // only add if not added
                        {
                            $("#EmailId").next(".field-validation-error").remove();
                                    $('#EmailId').css('border', '1px solid #AC004A');
                                    $("#EmailId").after("<div class='field-validation-error' style='color:#AC004A;margin-bottom: 20px;'>Email address is required*</div>");
                                   
                           
                        }
                        else {
                            $("#EmailId").next(".field-validation-error").remove(); // remove it
                               $('#EmailId').css('border', '1px solid black');
                           }
                    }
               
                }

After alerting return so that we can stop posting of form

                if (validationcontent.length != 0) {
                    return;
                }
       }
}