Amazon Ad

Thursday, 29 August 2013

How to get duplicate values from table in MS SQL Server

Here are some of the t-Sql queries you can use to find duplicate values

1. Using group by and having

select CabTransactions.TransactionId,y.cabid,y.orderid from
(
select min(cabid) as cabid,orderid,action from CabTransactions
group by cabid,orderid,action
having count(transactionid)>1
) as y,CabTransactions where y.cabid=CabTransactions.CabId and y.OrderId=CabTransactions.OrderId

2. Using not in

select * from cabtransactions where transactionid not in
(
    select min(transactionid) from cabtransactions group by cabid,orderid
)

Thanks
Ritesh

Tuesday, 27 August 2013

How to send POST parameters from jquery $.ajax to Web API ASP.NET MVC

Hi Guys,

I was facing a strange problem while sending data from jquery $.ajax to ASP.NET MVC Web API. I had earlier made lot of web appliactions using $.ajax with SOAP based (asmx),WCF (svc) files. But this time i struggled to post data into the web api's action.

I was having an Action like

 // POST api/values
        public string Post([FromBody]string value)
        {
            return value;
        }

When i tried this

$.ajax({
                 type: "POST",
                 dataType: "json",
                 contentType: 'application/json;charset=utf-8',
                 url: "/api/values",
                 data: {'value':'Test'},
                 success: function (data) {
                     alert(data);
                 },
                 error: function (error) {
                     jsonValue = jQuery.parseJSON(error.responseText);
                 }
             });

The value passed into "value" parameter of post was "null".

This is due to the following

1. Since web api requires the data to be in the format "=yourvalue". The existing $.ajax was not passing the data in post action.
2. The content type in $.ajax here is application/json, Where as the format as stated above is not a json format.

I successfully passed the post parameter by using the following

        $.ajax({
                 type: "POST",
                 dataType: "json",
                 url: "/api/values",
                 data: '=' + 'Test',
                 success: function (data) {
                     alert(data);
                 },
                 error: function (error) {
                     jsonValue = jQuery.parseJSON(error.responseText);
                 }
             });

As you can see i have not included "contentType: 'application/json;charset=utf-8'" in $.ajax. Also i have passed the data in the

format "=yourvalue" i.e data:'='+'Test', This passed the value "Test" in my post parameter i.e "value" in this case.

For complex types you use JSON.stringify i.e you can pass like

var complexdata= { 'value': 'Test','id':'350','name':'Ritesh' };

$.ajax({
                 type: "POST",
                 dataType: "json",
                 contentType: 'application/json;charset=utf-8',
                 url: "/api/values",
                 data: JSON.stringify(complexdata),
                 success: function (data) {
                     alert(data);
                 },
                 error: function (error) {
                     jsonValue = jQuery.parseJSON(error.responseText);
                 }
             });

For PUT in WEB API with $.ajax you can use like

var obj = {'Id':'3','EmpCode':'E001','EmpName':'Ritesh'};

             $.ajax({
                 type: "PUT",
                 dataType: "json",
                 contentType: 'application/json;charset=utf-8',
                 url: "/api/values/8",
                 data: JSON.stringify(obj),
                 success: function (data)
                 {
                     alert(data);
                 },
                 error: function (error) {
                     jsonValue = jQuery.parseJSON(error.responseText);
                 }
             });

Where your put method looks like

        // PUT api/values/5
        //To update an existing record
        public void Put(int id, [FromBody]Employee value)
        {

        }

Thanks
Ritesh Tandon

Thursday, 22 August 2013

How to run SQL server job based on linked server T-SQL

Hi Guys,

I was facing problem while running a job based on the linked server. I was having two sql servers and was implementing the concept of distributed databases.

I created a stored procedures which takes the data from my server database to remote server database. I wanted to create a job for this so that after every 1 hour my database is synchronized.

I did the following -:

Check which user is associated with the SQL server agent service, usually it is

NT Service\SQLSERVERAGENT

Now Create a new job

1. Add mapping user as
NT Service\SQLSERVERAGENT and for remote server give the user name and password.

2. Make sure the owner user is the same user who is having
administrator rights.

3. Do not add any user in the run as user textbox.

4. Add your step and the T-SQL command.

5. Execute the Job

That's it folks

Thanks
Ritesh

Tuesday, 13 August 2013

Update Columns Values From Another Table Column Values in MS SQL



Hi Guys,

Today i am going to tell you how to update column values from another table column values.


Lets Suppose I have two tables with the following structures. Now i want to update ItemTypeMaster table, the column supercategoryid is to be updated with values existing in the ItemCategoryMaster table's supercategory id column values. The Item_Cat_Id is Primary Key and CategoryId column in ItemTypeMaster table is Foreign Key.

ItemCategoryMaster Table
Item_Cat_Id    int,
Item_Cat_Desc    varchar(500),
Gender    varchar(1),
IsActive    bit,
SuperCategoryId    int,
Item_Cat_Picture    varchar(500)

ItemTypeMaster Table
ItemTypeId    int,
TypeName    varchar(50),
TypeDesc    varchar(500),
CategoryId    int,
SubCategoryId    int,
SuperCategoryId    int,
Gender    varchar(50),
ItemTypePicture    varchar(500),
IsActive    bit

Here is how to achieve the task.I was struggling to update my table column value based on a column value in another table. However i was surprised how the MS SQL update statements has got power of joins. We can use the joins in update query to update our column values.

The command i used to update the values is

update A set supercategoryid = B.supercategoryid
From ItemTypeMaster A
Inner Join itemcategorymaster B
On A.categoryid = B.item_cat_id

Similary, You can use select command to update the column values. For ex. I want to update IsActive column values based on the min id, The query would be:

update itemtypemaster set isactive=1 where itemtypeid in
(
select min(itemtypeid) from itemtypemaster
group by gender,supercategoryid,categoryid,subcategoryid,typename
)

Similarly, You can delete duplicate records from the table by using:

delete from itemtypemaster where itemtypeid not in
(
select min(itemtypeid) from itemtypemaster
group by gender,supercategoryid,categoryid,subcategoryid,typename
)


Hope this help guys!!

Thanks
Ritesh

Thursday, 8 August 2013

MVC 4 Form Validations With LINQ



Hi Guys,

Today i am going to tell you how to add validations on

a MVC form when LINQ is used.

The idea is to use MetadataType attribute and create a

partial class with the same name used in the LINQ

generated class.


Step 1. Create a table in the MS Sql database, with name Employee. Add columns
a. EmpId
b. EmpCode
c. EmpName

Step 2. Create Linq to Sql classes for the database with project name FirstAppDll.

Step 3. Create a model class for the employee

    [MetadataType(typeof(FirstAppDll.Employee))]
    public partial class Employee
    {
        [Required]
        public int EmpId { get; set; }

        [Required(ErrorMessage="Please Enter Employee Code")]
        [Range(3,12,ErrorMessage="Please Enter Employee Code Between 3 to 12 Characters")]
        public string EmpCode { get; set; }

        [Required(ErrorMessage="Please Enter Employee Name")]
        [StringLength(50,ErrorMessage="Employee Name Can Be Less Than 50 Characters")]
        public string EmpName { get; set; }
    }

Step 4. Your controller class should look like

// GET:/Employee/Create (For Blank Create Form)
        public ActionResult Create()
        {
            Employee emp = new Employee();
            return View(emp);
        }

        // POST:/Employee/Create (For saving the saved object from the form into the object)
        [HttpPost]
        public ActionResult Create(Employee obj)
        {
            if (ModelState.IsValid)
            {
                using (FirstAppDll.EmployeeLibraryDataContext context = new FirstAppDll.EmployeeLibraryDataContext())
                {
                    FirstAppDll.Employee emp = new FirstAppDll.Employee();
                    emp.EmpCode = obj.EmpCode;
                    emp.EmpName = obj.EmpName;
                    context.Employees.InsertOnSubmit(emp);
                    context.SubmitChanges();
                    return Redirect("/Employee/Create");
                }
            }
            return View(obj);
        }

Step 5. Generate the view by using the scaffolding for the partial class created. Generate the "Create" scaffold for the class Employee in the mvc project.


That's it folks, Check the form by typing localhost:yourport/Employee/Create and the validations are ready for you.

Thanks
Ritesh

Monday, 29 July 2013

sqlite3 NotImplementedError C extension support is not enabled Pass -xcert.enabled=true to JRuby

Hi Folks,

I was working on Ruby on Rails on Windows 7 platform. I was following a tutorial and was stucked when i ran rake routes command to generate the "resource". When i ran "rake routes" command i got the error

"Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension.
    /Users/nainirajk/.rvm/rubies/jruby-1.7.0/bin/jruby extconf.rb
          NotImplementedError: C extension support is not enabled. Pass -Xcext.enabled=true to JRuby or set JRUBY_OPTS or modify .jrubyrc to enable."

Here is how i was able to solve the problem

Step 1: Open GemFile present in your project folder. Edit the GemFile.

Step 2: Find "gem sqlite3" in the GemFile. Comment the line "gem sqlite3" and after the commented line add gem 'activerecord-jdbcsqlite3-adapter', :require => 'jdbc-sqlite3', :require=>'arjdbc'.

i.e

#gem 'sqlite3'
gem 'activerecord-jdbcsqlite3-adapter', :require => 'jdbc-sqlite3', :require=>'arjdbc'

Step 3.Open a new command prompt window and type "bundle install".

Step 4. After installing all the bundles successfully, run the command related to sqlite3 for e.x "rake routes".

This solved my problem.

Thanks
Ritesh Tandon

Sunday, 28 July 2013

Copy data of one table into another table in MS SQL

Hi Folks,

Today i am going to tell you how to copy data of one table into another table. There are basically conditions for this

1. Destination table (The table which would have the new data) exists in the database
2. Destination table (The table which would have the new data) does not exists in the database

 For both these conditions seperate MS SQL commands are used.

1.When the table doesn't exists and the data is to be fetched from a temporary table.

select * into [tablename] from #[temptablename]

2. When the table exists in the database and the data is to be fetched from a temporary table.

insert into [tablename]
select * from #[temptablename]

Thanks
Ritesh

Saturday, 20 July 2013

Not able to create connection with app.config in Class Library project.

Hi Folks,

I was struggling to make a connection in my VB.NET windows application project from my Class Library dll which was having the connectionstring information. When i debugged it i found that the default connectionstring was coming instead of my configuration settings.

When i investigated i found the solution. The problem is App.config's setting is not visible to the .exe file. We need a mechanism to tell the exe file to take the connectionstring from the environment.

Which i did it like this

Step 1. Right click on the project (Class Library Project).

Step 2. Click on properties option.

Step 3. Select "Settings" tab.

Step 4. Create a new connection string here. i.e

a. In the name column give your connectionstring name.
b. In the type colyumn select "(connection string)".
c. In the scope column select "Application".

and save the settings.

When you have followed the above steps, It would automatically creat a new connectionstring in the app.config file. Copy the exact connectionstring name and paste it in your code where you are using connectionstring name. The name is usually like YourProjectName.Properties.Settings.ConnectionStringName.

Thats it folks the problem is solved and you can create a secure connectionstring in VB.NET or in ASP.NET.

Monday, 8 July 2013

Form Validation Using Javascript and Regular Expressions

Hi Guys,

 I was working in asp.net, There was a signup form and client wanted sophisticated validations on the form at the client side. Using validations was a cumbersome task as it requires complexities and user inputs.

I managed to create my own javascript file which validates any form and html controls by the use of the "name" attribute of the tag. You need to pass the div name which has the form or html controls which you want to validate.  In this example my form was in the html table, You can customize the javascript code based on the parent elements.

Here is my javascript file, Which must be included in the page to validate the page.

 /*---------------------------------Javascript Code Starts Here-------------------------------*/
//matches only characters, no special characters and range is from 3-50 characters
        //var match_first_name = /^([a-zA-Z]+){3,50}$/;

        //matches only characters, no special characters and range is from 2-50 characters.
        //Added the constraint of non required number after first name [space] [any number].
        var match_first_name = /^(([a-zA-Z]+){3,50})(\s\S\d{0,1})?$/;

        //matches only characters, no special characters and range is from 2-50 characters.
        //Added the constraint of non required number after first name [space] [any number].
        var match_last_name = /^(([a-zA-Z]+){3,50})(\s\S\d{0,1})?$/;

        //matches email, no special characters and name range is 1 to 250 then domain characters are from 1 to 250 and (.in .com) i.e 2 to 3 characters can be there.
        var match_email = /^((([a-zA-z]+(\.[a-zA-z0-9])?){1,250})(\d{0,30})?)\@((([a-zA-z]+){1,250}))\.(([a-zA-z]+){2,5})$/;

        //matches phone number in the format (223) 323-3726 i.e (xxx) xxx-xxxx. Only 14 characters can be added
        var match_phone = /^(\(\d{3}\)\s\d{3}\-\d{4})$/;

        //matches the password the password can have special characters as well as numbers.
        //var match_password = /^([a-zA-Z0-9@!#$%*&^.]{8,30})$/;

        //matches the password having any string 4 to 8 characters
        //var match_password = /^.{4,8}$/;

        //matches the password expression that requires one lower case letter, one upper case letter, one digit, 6-33 length, and no spaces.
        var match_password = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).{6,33}$/;

        //matches the height and can have numeric or decimal values in the range of xx.xx
        var match_height = /^[0-9]{1,2}((\.)\d{0,2})?$/

        //matches the height and can have numeric or decimal values in the range of xx.xx
        var match_weight = /^[0-9]{1,3}((\.)\d{0,2})?$/

        var count = 0;

        function check(divname, showerrmsg) {
            var val = '';
            var result = true;
            var pwd = '';
            $("#" + divname + " table input").each(function (index, el) {
                val = $(el).val();
                if (($(el).attr('name').indexOf('FirstName') != -1) || ($(el).attr('name').indexOf('firstname') != -1)) {
                    result = match_first_name.test(val);
                    if (result == false) {
                        $(el).addClass("error");

                        if (showerrmsg == true)
                            alert('Incorrect name format, Please enter more than 2 and less than 50 characters without any numbers, spaces or special characters.');

                        return false;
                    }
                    else {
                        $(el).removeClass("error");
                    }
                }
                else if (($(el).attr('name').indexOf('LastName') != -1) || ($(el).attr('name').indexOf('lastname') != -1)) {
                    result = match_last_name.test(val);
                    if (result == false) {
                        $(el).addClass("error");

                        if (showerrmsg == true)
                            alert('Incorrect name format, Please enter more than 2 and less than 50 characters without any numbers, spaces or special characters.');

                        return false;
                    }
                    else {
                        $(el).removeClass("error");
                    }
                }
                else if (($(el).attr('name').indexOf('Email') != -1) || ($(el).attr('name').indexOf('email') != -1)) {
                    result = match_email.test(val);
                    if (result == false) {
                        $(el).addClass("error");

                        if (showerrmsg == true)
                            alert('Please enter a valid email address.');

                        return false;
                    }
                    else {
                        $(el).removeClass("error");
                    }
                }
                else if (($(el).attr('name').indexOf('Phone') != -1) || ($(el).attr('name').indexOf('phone') != -1)) {
                    result = match_phone.test(val);
                    if (result == false) {
                        $(el).addClass("error");

                        if (showerrmsg == true)
                            alert('Please enter valid US phone number. eg. (xxx) xxx-xxxx');

                        return false;
                    }
                    else {
                        if (val == "(000) 000-0000") {

                            if (showerrmsg == true)
                                alert("Invalid Phone Number");

                            $(el).addClass("error");
                            result = false;
                            return false;
                        }
                        else {
                            $(el).removeClass("error");
                        }
                    }
                }
                else if (($(el).attr('name').indexOf('ConfirmPassword') != -1) || ($(el).attr('name').indexOf('confirmpassword') != -1)) {
                    result = match_password.test(val);
                                       if (val == pwd) {
                        $(el).removeClass("error");
                    }
                    else {

                        if (showerrmsg == true)
                            alert("Password Doesn't Match");

                        result = false;
                        $(el).addClass("error");
                        return false;
                    }
                }
                else if (($(el).attr('name').indexOf('Password') != -1) || ($(el).attr('name').indexOf('password') != -1)) {
                    pwd = val;
                    result = match_password.test(val);
                    if (result == false) {
                        $(el).addClass("error");

                        if (showerrmsg == true)
                            alert('Please enter valid password having 6 to 13 characters, One lower case letter, one upper case letter and one digit.');

                        return false;
                    }
                    else {
                        $(el).removeClass("error");
                    }
                }
                else if (($(el).attr('name').indexOf('height') != -1) || ($(el).attr('name').indexOf('height') != -1)) {
                    result = match_height.test(val);

                    var msg = 'Please enter valid height. eg. xx.xx';
                    if (result != false) {
                        if (eval($(el).val()) <= 0) {
                            msg = 'Height cannot be zero.';
                            result = false;
                        }
                    }

                    if (result == false) {
                        $(el).addClass("error");

                        if (showerrmsg == true)
                            alert(msg);

                        return false;
                    }
                    else {
                        $(el).removeClass("error");
                    }
                }
                else if (($(el).attr('name').indexOf('weight') != -1) || ($(el).attr('name').indexOf('weight') != -1)) {
                    result = match_weight.test(val);
                    var msg = 'Please enter valid weight. eg. xxx.xx';
                    if (result != false) {
                        if (eval($(el).val()) <= 0) {
                            msg = 'Weight cannot be zero.';
                            result = false;
                        }
                    }

                    if (result == false) {
                        $(el).addClass("error");

                        if (showerrmsg == true) {
                            alert(msg);
                        }


                        return false;
                    }
                    else {
                        $(el).removeClass("error");
                    }
                }
                else if (($(el).attr('name').indexOf('registeration') != -1) || ($(el).attr('name').indexOf('Registeration') != -1)) {
                    if ($(el).val().trim() == "")
                        result = false;

                    if (result == false) {
                        $(el).addClass("error");

                        if (showerrmsg == true)
                            alert('Please enter registeration number');

                        return false;
                    }
                    else {
                        $(el).removeClass("error");
                    }
                }
                else if (($(el).attr('name').indexOf('image') != -1) || ($(el).attr('name').indexOf('FileUpload') != -1)) {

                    if (showerrmsg) {
                        var _validFileExtensions = [".jpg", ".jpeg", ".bmp", ".gif", ".png"];
                        var oInput = $(el);

                        //Check extension
                        if ($(oInput).attr('type') == "file") {
                            var sFileName = $(oInput).val();
                            if (sFileName.length > 0 || $(el).attr('name') == "FileUpload1") {
                                var blnValid = false;
                                for (var j = 0; j < _validFileExtensions.length; j++) {
                                    var sCurExtension = _validFileExtensions[j];
                                    if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
                                        blnValid = true;
                                        break;
                                    }
                                }
                                if (!blnValid) {
                                    alert("Sorry, Please select a file, having extensions " + _validFileExtensions.join(", ") + " with a maximum size of 1MB.");
                                    $(el).addClass("error");
                                    result = false;
                                    return false;
                                }
                                else {
                                    $(el).removeClass("error");
                                }
                            }
                        }

                        //Check filesize
                        if (window.FileReader) {
                            file = oInput.size;
                            size = file;
                            var files = document.getElementById($(el).attr('id')).files;
                            if (files[0].size > 1048576) {
                                alert('File size should be less than 1MB');
                                result = false;
                            }
                        }
                    } //end of if(showerrmsg)
                }
            });
            showerrmsg = false;
            return result;
        }

        function initialize(divname) {
            $("#" + divname + " table input").each(function (index, el) {

                if($(el).attr("type")!="file")
                    $(el).bind("blur", function () { check(divname, false); });

                if($(el).attr("type")=="submit")
                    $(el).bind("blur", function () { check(divname, true); });
            });

            $("#" + divname + " table input").each(function (index, el) {
                $(el).bind("keydown", function (event) { if (len($(el).val()) > $(el).attr('maxlength')) event.preventDefault(); });
            });
        }
 /*---------------------------------Javascript Code Ends Here-------------------------------*/

To Run the above you need to include the javascript code/file in the page you want your validations. In your page add the following lines

<script>
 $(document).ready({ initialize(your_div_name_having_form);});
</script>

Thanks
Ritesh

Form Validation Using Javascript and Regular Expressions

Hi Guys,

 I was working in asp.net, There was a signup form and client wanted sophisticated validations on the form at the client side. Using validations was a cumbersome task as it requires complexities and user inputs.

I managed to create my own javascript file which validates any form and html controls by the use of the "name" attribute of the tag. You need to pass the div name which has the form or html controls which you want to validate.  In this example my form was in the html table, You can customize the javascript code based on the parent elements.

Here is my javascript file, Which must be included in the page to validate the page.

 /*---------------------------------Javascript Code Starts Here-------------------------------*/
//matches only characters, no special characters and range is from 3-50 characters
        //var match_first_name = /^([a-zA-Z]+){3,50}$/;

        //matches only characters, no special characters and range is from 2-50 characters.
        //Added the constraint of non required number after first name [space] [any number].
        var match_first_name = /^(([a-zA-Z]+){3,50})(\s\S\d{0,1})?$/;

        //matches only characters, no special characters and range is from 2-50 characters.
        //Added the constraint of non required number after first name [space] [any number].
        var match_last_name = /^(([a-zA-Z]+){3,50})(\s\S\d{0,1})?$/;

        //matches email, no special characters and name range is 1 to 250 then domain characters are from 1 to 250 and (.in .com) i.e 2 to 3 characters can be there.
        var match_email = /^((([a-zA-z]+(\.[a-zA-z0-9])?){1,250})(\d{0,30})?)\@((([a-zA-z]+){1,250}))\.(([a-zA-z]+){2,5})$/;

        //matches phone number in the format (223) 323-3726 i.e (xxx) xxx-xxxx. Only 14 characters can be added
        var match_phone = /^(\(\d{3}\)\s\d{3}\-\d{4})$/;

        //matches the password the password can have special characters as well as numbers.
        //var match_password = /^([a-zA-Z0-9@!#$%*&^.]{8,30})$/;

        //matches the password having any string 4 to 8 characters
        //var match_password = /^.{4,8}$/;

        //matches the password expression that requires one lower case letter, one upper case letter, one digit, 6-33 length, and no spaces.
        var match_password = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).{6,33}$/;

        //matches the height and can have numeric or decimal values in the range of xx.xx
        var match_height = /^[0-9]{1,2}((\.)\d{0,2})?$/

        //matches the height and can have numeric or decimal values in the range of xx.xx
        var match_weight = /^[0-9]{1,3}((\.)\d{0,2})?$/

        var count = 0;

        function check(divname, showerrmsg) {
            var val = '';
            var result = true;
            var pwd = '';
            $("#" + divname + " table input").each(function (index, el) {
                val = $(el).val();
                if (($(el).attr('name').indexOf('FirstName') != -1) || ($(el).attr('name').indexOf('firstname') != -1)) {
                    result = match_first_name.test(val);
                    if (result == false) {
                        $(el).addClass("error");

                        if (showerrmsg == true)
                            alert('Incorrect name format, Please enter more than 2 and less than 50 characters without any numbers, spaces or special characters.');

                        return false;
                    }
                    else {
                        $(el).removeClass("error");
                    }
                }
                else if (($(el).attr('name').indexOf('LastName') != -1) || ($(el).attr('name').indexOf('lastname') != -1)) {
                    result = match_last_name.test(val);
                    if (result == false) {
                        $(el).addClass("error");

                        if (showerrmsg == true)
                            alert('Incorrect name format, Please enter more than 2 and less than 50 characters without any numbers, spaces or special characters.');

                        return false;
                    }
                    else {
                        $(el).removeClass("error");
                    }
                }
                else if (($(el).attr('name').indexOf('Email') != -1) || ($(el).attr('name').indexOf('email') != -1)) {
                    result = match_email.test(val);
                    if (result == false) {
                        $(el).addClass("error");

                        if (showerrmsg == true)
                            alert('Please enter a valid email address.');

                        return false;
                    }
                    else {
                        $(el).removeClass("error");
                    }
                }
                else if (($(el).attr('name').indexOf('Phone') != -1) || ($(el).attr('name').indexOf('phone') != -1)) {
                    result = match_phone.test(val);
                    if (result == false) {
                        $(el).addClass("error");

                        if (showerrmsg == true)
                            alert('Please enter valid US phone number. eg. (xxx) xxx-xxxx');

                        return false;
                    }
                    else {
                        if (val == "(000) 000-0000") {

                            if (showerrmsg == true)
                                alert("Invalid Phone Number");

                            $(el).addClass("error");
                            result = false;
                            return false;
                        }
                        else {
                            $(el).removeClass("error");
                        }
                    }
                }
                else if (($(el).attr('name').indexOf('ConfirmPassword') != -1) || ($(el).attr('name').indexOf('confirmpassword') != -1)) {
                    result = match_password.test(val);
                                       if (val == pwd) {
                        $(el).removeClass("error");
                    }
                    else {

                        if (showerrmsg == true)
                            alert("Password Doesn't Match");

                        result = false;
                        $(el).addClass("error");
                        return false;
                    }
                }
                else if (($(el).attr('name').indexOf('Password') != -1) || ($(el).attr('name').indexOf('password') != -1)) {
                    pwd = val;
                    result = match_password.test(val);
                    if (result == false) {
                        $(el).addClass("error");

                        if (showerrmsg == true)
                            alert('Please enter valid password having 6 to 13 characters, One lower case letter, one upper case letter and one digit.');

                        return false;
                    }
                    else {
                        $(el).removeClass("error");
                    }
                }
                else if (($(el).attr('name').indexOf('height') != -1) || ($(el).attr('name').indexOf('height') != -1)) {
                    result = match_height.test(val);

                    var msg = 'Please enter valid height. eg. xx.xx';
                    if (result != false) {
                        if (eval($(el).val()) <= 0) {
                            msg = 'Height cannot be zero.';
                            result = false;
                        }
                    }

                    if (result == false) {
                        $(el).addClass("error");

                        if (showerrmsg == true)
                            alert(msg);

                        return false;
                    }
                    else {
                        $(el).removeClass("error");
                    }
                }
                else if (($(el).attr('name').indexOf('weight') != -1) || ($(el).attr('name').indexOf('weight') != -1)) {
                    result = match_weight.test(val);
                    var msg = 'Please enter valid weight. eg. xxx.xx';
                    if (result != false) {
                        if (eval($(el).val()) <= 0) {
                            msg = 'Weight cannot be zero.';
                            result = false;
                        }
                    }

                    if (result == false) {
                        $(el).addClass("error");

                        if (showerrmsg == true) {
                            alert(msg);
                        }


                        return false;
                    }
                    else {
                        $(el).removeClass("error");
                    }
                }
                else if (($(el).attr('name').indexOf('registeration') != -1) || ($(el).attr('name').indexOf('Registeration') != -1)) {
                    if ($(el).val().trim() == "")
                        result = false;

                    if (result == false) {
                        $(el).addClass("error");

                        if (showerrmsg == true)
                            alert('Please enter registeration number');

                        return false;
                    }
                    else {
                        $(el).removeClass("error");
                    }
                }
                else if (($(el).attr('name').indexOf('image') != -1) || ($(el).attr('name').indexOf('FileUpload') != -1)) {

                    if (showerrmsg) {
                        var _validFileExtensions = [".jpg", ".jpeg", ".bmp", ".gif", ".png"];
                        var oInput = $(el);

                        //Check extension
                        if ($(oInput).attr('type') == "file") {
                            var sFileName = $(oInput).val();
                            if (sFileName.length > 0 || $(el).attr('name') == "FileUpload1") {
                                var blnValid = false;
                                for (var j = 0; j < _validFileExtensions.length; j++) {
                                    var sCurExtension = _validFileExtensions[j];
                                    if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
                                        blnValid = true;
                                        break;
                                    }
                                }
                                if (!blnValid) {
                                    alert("Sorry, Please select a file, having extensions " + _validFileExtensions.join(", ") + " with a maximum size of 1MB.");
                                    $(el).addClass("error");
                                    result = false;
                                    return false;
                                }
                                else {
                                    $(el).removeClass("error");
                                }
                            }
                        }

                        //Check filesize
                        if (window.FileReader) {
                            file = oInput.size;
                            size = file;
                            var files = document.getElementById($(el).attr('id')).files;
                            if (files[0].size > 1048576) {
                                alert('File size should be less than 1MB');
                                result = false;
                            }
                        }
                    } //end of if(showerrmsg)
                }
            });
            showerrmsg = false;
            return result;
        }

        function initialize(divname) {
            $("#" + divname + " table input").each(function (index, el) {

                if($(el).attr("type")!="file")
                    $(el).bind("blur", function () { check(divname, false); });

                if($(el).attr("type")=="submit")
                    $(el).bind("blur", function () { check(divname, true); });
            });

            $("#" + divname + " table input").each(function (index, el) {
                $(el).bind("keydown", function (event) { if (len($(el).val()) > $(el).attr('maxlength')) event.preventDefault(); });
            });
        }
 /*---------------------------------Javascript Code Ends Here-------------------------------*/

To Run the above you need to include the javascript code/file in the page you want your validations. In your page add the following lines

<script>
 $(document).ready({ initialize(your_div_name_having_form);});
</script>

Thanks
Ritesh

Thursday, 4 July 2013

Disable Dates In Tigra Calendar After Current Date

Hi,

I was working in Tigra Calendar which is a really good javascript calendar library. I was stucked when there was a need to disable dates after the current date. Here is how i was able to solve the problem.

Step 1: Edit tcal.css and add the following lines

div#tcal td.disabled_days {
font-style: italic;
color: silver;
cursor: auto;
}

Step 2: Edit tcal.js and go to the function f_tcalGetHTML (d_date)

After the lines :
if (d_current.getMonth() != d_date.getMonth())
                a_class[a_class.length] = s_pfx + 'OtherMonth';
           
if (d_current.getDay() == 0 || d_current.getDay() == 6)
            a_class[a_class.length] = s_pfx + 'Weekend';
           
if (d_current.valueOf() == d_today.valueOf())
                a_class[a_class.length] = s_pfx + 'Today';
           
if (d_current.valueOf() == d_selected.valueOf())
                a_class[a_class.length] = s_pfx + 'Selected';

And Before the line
d_current.setDate(++n_date)

Add these lines
//start of ritesh's code
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();
if (dd < 10) { dd = '0' + dd } if (mm < 10) { mm = '0' + mm } today = mm + '/' + dd + '/' + yyyy;
today=new Date(today);

var dd1 = d_current.getDate();
var mm1 = d_current.getMonth() + 1; //January is 0!
var yyyy1 = d_current.getFullYear();
if (dd1 < 10) { dd1 = '0' + dd1 } if (mm1 < 10) { mm1 = '0' + mm1 } d_current_1 = mm1 + '/' + dd1 + '/' + yyyy1;
d_current_1=new Date(d_current_1);

//Check if the date of calendar is less than today's date
if (d_current_1 <= today) {
   //default code
    s_html += '<td' + f_tcalRelDate(d_current) + (a_class.length ? ' class="' + a_class.join(' ') + '">' : '>') + n_date + '</td>';
}
else {
    s_html += '<td class="disabled_days">' + n_date + '</td>'
}


And That's It!! Check the calendar the dates after the current dates would be disabled .


Thanks
Ritesh Tandon

How to implement Captcha v3 in ASP.NET

 I was facing an issue of dom parsing in my website. I finally resolved it by using Google Captcha V3. Step 1: Get your keys from https:...