Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"? in H:\root\home\sklibraries-001\www\rajmhr\wp-content\plugins\wp-markdown\markdownify\markdownify.php on line 299
Input Validation – (Rules Framework) – RajTech

Input Validation – (Rules Framework)

Rules Framework:

It is a framework created for proper error handling or validating user input fields. A good software design is a one whose code is based on certain principles i.e. a framework that allows us to manage codes effectively. And I found this framework is really effective to manage

Practice of validating is just a method in the class file whether something is true or false. Even I used to wrap input validation in some particular function and check whether it is valid or not. This is the common methodology  and this one is no different than that.

The Rules Framework is only a implementation of  Factory method design pattern. You can clearly see the class “RulesFactory” is a factory class which holds multiple classes of different rules. “StudentRuleSet” and “CustomerRuleSet” are rule set classes that defines rules for each class i.e StudentRulesSet for Student class and CustomerRuleSet for Customer. IRuleSet is an Interface which has single method to implement “void apply(object obj);”. All of the rules will be defined in the apply method to apply rules for validation and handling and input will be validated by custom exception class, in this case we have “RulesException”.

So it is very clear that, to validate the input field of each form(might be multiple form only 2 for demo.) we create different rule set class and implement the method apply to validate. So it is very simple and straight forward.

There might be different rules for the each new class and form. Let take a Customer Form which has multiple things to validate and handle.

Rules:

  1. Fields cannot be empty
  2. Username and password cannot be same.
  3. Password must match with RePassword
  4. CustomerID must be Numeric type
  5. Mobile number must be numeric with 10 digit long.

So we are going to validate and handle these five rules.

To be more clear how things are working, lets check out class diagram.

This is the relationship between classes. Now its time to check some working code. I have included classes that we use in this framework. Lets make little bit clear about Classes in class diagram:

Program: Main starting Class

StudentForm: Student form (class)

Customer: Customer form (class)

RulesFactory: Factory that gives the required RulsetClass

CustomerRuleSet: Rules defined for customer form.

IRuleSet: Interface which has a single method, which is implemented by RuleSet classes.

MyException: Custom exception to catch error or in put validation.

namespace RulesFramwork
{
    public partial class Customer : Form
    {
        public Customer()
        {
            InitializeComponent();
        }
        public string UserName
        {
            get { return txtUserName.Text; }
        }
        public string Password
        {
            get { return txtPassword.Text; }
        }
        public string RePassword
        {
            get { return txtRePassword.Text; }
        }
        public string Mobile
        {
            get { return txtMobile.Text; }
        }
        public string CustomerId
        {
            get { return txtCustomerId.Text; }
        }
        private void btnRegister_Click(object sender, EventArgs e)
        {
            try
            {
                IRuleSet reuRuleSet = RuleSetFactory.GetRuleSet(RuleSetFactory.RulesItem.Customer);
                reuRuleSet.ApplyRules(this);
                MessageBox.Show("Validated..");
            }
            catch (RuleException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RulesFramwork
{
    public class RuleSetFactory
    {
        static readonly Dictionary<RulesItem, IRuleSet> Objs;
        public enum RulesItem
        {
            Student,
            Customer
        }
        static RuleSetFactory()
        {
            Objs = new Dictionary<RulesItem, IRuleSet>
            {
                {
                    RulesItem.Student, new StudentRuleSet()
                },
                {
                    RulesItem.Customer, new CustomerRuleSet()
                }
            };
        }
        public static IRuleSet GetRuleSet(RulesItem item)
        {
            var result = Objs.ContainsKey(item);
            if (result)
                return Objs[item];
            throw new RuleException("No Rules found");
        }
    }
}
namespace RulesFramwork
{
    public interface IRuleSet
    {
        void ApplyRules(object st);
    }
namespace RulesFramwork
{
    class CustomerRuleSet : IRuleSet
    {
        private Customer _customer;
        public void ApplyRules(object st)
        {
            _customer = (Customer)st;
//Rule 1.
            CheckEmptyFields();
//Rule 3
            ValidateIdField();
//Rule 4
            ValidateMobileNo();
//Rule 2/3
            CheckPassword();
        }
        private void CheckPassword()
        {
            if (_customer.UserName.Equals(_customer.Password))
            {
                throw new RuleException("Firstname and lastname cannot be same.");
            }
            else if (!_customer.Password.Equals(_customer.RePassword))
            {
                throw new RuleException("Password missmatch");
            
            }
        }
        private void ValidateMobileNo()
        {
            if (!_customer.Mobile.IsNumeric() || _customer.Mobile.Length != 10)
            {
                throw new RuleException("Mobile nuber must contain numbers and only 10 digit long.");
            }
        }
        private void ValidateIdField()
        {
            if (!_customer.CustomerId.IsNumeric() || _customer.CustomerId.Length<=5)
            {
                throw new RuleException("Customer Id must be numeric and length must be 6 or more");
            }
        }
        private void CheckEmptyFields()
        {
            if (_customer.UserName.Equals("") || _customer.Password.Equals("") || _customer.RePassword.Equals("") || _customer.CustomerId.Equals("") || _customer.RePassword.Equals(""))
            {
                throw new RuleException("Fields cannot be empty.");
            }
        }
    }
}

So these are the classes you need to build. That’s it. Now in the validate or submit  event you need to get appropriate rule set and apply from factory method i.e. RuleSetFactory class. Code below is button click event of customer. This looks manageable and clean code to validate all in couple of lines. If you want to add more rules you will be adding on its respective rule set class. Cool??????

private void btnRegister_Click(object sender, EventArgs e)
       {
           try
           {
//Get appropriate rule set
               IRuleSet reuRuleSet = RuleSetFactory.GetRuleSet(RuleSetFactory.RulesItem.Customer);
// apply the rules
               reuRuleSet.ApplyRules(this);
               MessageBox.Show("Validated..");
           }
           catch (RuleException ex)
           {
               MessageBox.Show(ex.Message);
           }

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *