Wednesday, 15 April 2015

.Net Multifield US Canada Phone Validation Attribute

> C#/.Net Samples

This validation covers the US and Canada phone validation input into three different text boxes.

The number is like

123-456-7890


Credits: Jason Watson

Use

[MultiFieldPhone(FieldOne = "PhoneAreaCode", FieldTwo = "PhonePrefix", FieldThree = "PhoneLastFour", ErrorMessage = "Please enter valid phone number.")]
public String PhoneAreaCode { get; set; }
 
[MultiFieldPhone(FieldOne = "PhoneAreaCode", FieldTwo = "PhonePrefix", FieldThree = "PhoneLastFour", ErrorMessage = "Please enter valid phone number.")]
public String PhonePrefix { get; set; }
 
[MultiFieldPhone(FieldOne = "PhoneAreaCode", FieldTwo = "PhonePrefix", FieldThree = "PhoneLastFour", ErrorMessage = "Please enter valid phone number.")]
public String PhoneLastFour { get; set; } 

RegEx

public const string NumbersOnly = @"^[0-9]+$";
Or for more control you can change the checking and use the following regex
public const string PhoneUs = @"^[2-9]\d{2}[-]\d{3}[-]\d{4}$"; //^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$
 

Attribute Code

public class MultiFieldPhoneAttribute : ValidationAttribute, IClientValidatable
    {
        public string FieldOne { get; set; }
        public string FieldTwo { get; set; }
        public string FieldThree { get; set; }
 
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var valThis = value;
 
            var baseFieldOneInfo = validationContext.ObjectType.GetProperty(FieldOne);
            var valFieldOne = baseFieldOneInfo.GetValue(validationContext.ObjectInstance, null);
 
            var baseFieldTwoInfo = validationContext.ObjectType.GetProperty(FieldTwo);
            var valFieldTwo = baseFieldTwoInfo.GetValue(validationContext.ObjectInstance, null);
 
            var baseFieldThreeInfo = validationContext.ObjectType.GetProperty(FieldThree);
            var valFieldThree = baseFieldThreeInfo.GetValue(validationContext.ObjectInstance, null);
 
            ValidationResult result = null;
 
            if (valThis != null || valFieldOne != null || valFieldTwo != null || valFieldThree != null)
            {
                var rgx = new Regex(ValidationRegExRules.NumbersOnly);
                if (valFieldOne == null || valFieldTwo == null || valFieldThree == null || valThis == null)
                {
                    result = new ValidationResult(base.ErrorMessage);
                }
                else if (valFieldOne.ToString().Length < 3 || valFieldTwo.ToString().Length < 3 || valFieldThree.ToString().Length < 4)
                {
                    result = new ValidationResult(base.ErrorMessage);
                } else if (!rgx.IsMatch(valFieldOne.ToString()) || !rgx.IsMatch(valFieldTwo.ToString()) ||
                    !rgx.IsMatch(valFieldThree.ToString()))
                {
                    result = new ValidationResult(base.ErrorMessage);
                }
            }
            return result;
        }
 
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata,
            ControllerContext context)
        {
            var errorMessage = this.FormatErrorMessage(metadata.DisplayName);
            var compareRule = new ModelClientValidationRule();
            compareRule.ErrorMessage = errorMessage;
            compareRule.ValidationType = "multifieldphone";
            compareRule.ValidationParameters.Add("fieldone", FieldOne);
            compareRule.ValidationParameters.Add("fieldtwo", FieldTwo);
            compareRule.ValidationParameters.Add("fieldthree", FieldThree);
            yield return compareRule;
        }
    }


Client Side Code

(function ($) {
     
    //#endregion MultiFieldPhone Validation Rule
 
    $.validator.addMethod("multifieldphone", function (value, element, params) {
        var fields = params.split(",");
 
        var fieldOne = $("#" + fields[0]);
        var fieldTwo = $("#" + fields[1]);
        var fieldThree = $("#" + fields[2]);
 
        var numbersOnlyRegEx = "^[0-9]+$";
 
        var isValid = true;
        var i;
 
        if (value == "" || !value.match(numbersOnlyRegEx)) {
            isValid = false;
        } else {
            if (!jQuery.inArray($(':focus').attr("id"), fields)) {
                for (i = 0; i < fields.length; i++) {
                    if ($("#" + fields[i]) == null || $("#" + fields[i]).val() == "") {
                        isValid = false;
                    }
                }
            } else if ((fieldOne != null && (fieldOne.val().length < 3 || !fieldOne.val().match(numbersOnlyRegEx))) ||
                (fieldTwo != null && (fieldTwo.val().length < 3 || !fieldTwo.val().match(numbersOnlyRegEx))) ||
                (fieldThree != null && (fieldThree.val().length < 4 || !fieldThree.val().match(numbersOnlyRegEx)))) {
                isValid = false;
            }
        }
 
        for (i = 0; i < fields.length; i++) {
            if (!isValid) {
                if ($("#" + fields[i]) != null && !$("#" + fields[i]).hasClass("input-validation-error")) {
                    $("#" + fields[i]).addClass("input-validation-error");
                }
            } else {
                if ($("#" + fields[i]) != null && $("#" + fields[i]).hasClass("input-validation-error")) {
                    $("#" + fields[i]).removeClass("input-validation-error");
                }
            }
        }
 
        return isValid;
    });
 
    $.validator.unobtrusive.adapters.add("multifieldphone", ["fieldone", "fieldtwo", "fieldthree"], function (options) {
        options.rules["multifieldphone"] = options.params.fieldone + "," + options.params.fieldtwo + "," + options.params.fieldthree;
        options.messages["multifieldphone"] = options.message;
    });
 
    //#endregion MultiFieldPhone Validation Rules
 
}(jQuery));