电话代码前缀号码mvc自定义验证

时间:2014-11-26 00:22:30

标签: asp.net-mvc validation data-annotations custom-attributes

我已经按照不同的示例提出了一个自定义验证器来检查电话号码。我的号码分为三个不同的领域。我只是想确保如果提供了电话号码,那么所有三个字段都应该包含一些内容。当我单击提交按钮时,我得到我已应用此属性的字段的值。 Now for the other two fields, i am getting the wrong id and due to this, the value is undefined as showing in this image。我在这做错了什么?我不想将手机字段移出学生班级并进入视图模型。

enter image description here

看起来我的问题是如何指定其他属性

[PhoneCodePrefixNumber(FieldOne = "HomePhoneAreaCode", FieldTwo = "HomePhonePrefix", ErrorMessage = "You must enter all three parts of the phone number.")]

如果我按照我的结构更改id(Student_HomePhoneAreaCode和Student_HomePhonePrefix),那么属性代码会抛出一个错误,因为ids是错误的,这一行返回null

var baseFieldOneInfo = validationContext.ObjectType.GetProperty(FieldOne);

页面上显示的ID是,视图模型将学生类作为属性:

  1. Student_HomePhoneAreaCode
  2. Student_HomePhonePrefix
  3. Student_HomePhoneLastFour
  4. 这是页面中的html。如果你看第三个输入,那么我的另外两个字段data-val-phonecodeprefixnumber-fieldone="HomePhoneAreaCode" data-val-phonecodeprefixnumber-fieldtwo="HomePhonePrefix"中的ID是错误的。

    <input class="autoTabElement" data-val="true" data-val-digits="Please input only numbers for area code." data-val-length="Please input 3 numbers for the area code." data-val-length-max="3" data-val-length-min="3" id="Student_HomePhoneAreaCode" maxlength="3" name="Student.HomePhoneAreaCode" style="width:26px;" type="text" value="816" />&nbsp;
    <input class="autoTabElement" data-val="true" data-val-digits="Please input only numbers for phone prefix." data-val-length="Please input 3 numbers for the phone prefix." data-val-length-max="3" data-val-length-min="3" id="Student_HomePhonePrefix" maxlength="3" name="Student.HomePhonePrefix" style="width:26px;" type="text" value="525" />&nbsp;
    <input class="autoTabElement" data-val="true" data-val-digits="Please input only numbers for phone number." data-val-length="Please input 4 numbers for the phone number." data-val-length-max="4" data-val-length-min="4" data-val-phonecodeprefixnumber="You must enter all three parts of the phone number." data-val-phonecodeprefixnumber-fieldone="HomePhoneAreaCode" data-val-phonecodeprefixnumber-fieldtwo="HomePhonePrefix" id="Student_HomePhoneLastFour" maxlength="4" name="Student.HomePhoneLastFour" style="width:32px;" type="text" value="2201" />
    <br /><span class="field-validation-valid" data-valmsg-for="Student.HomePhoneAreaCode" data-valmsg-replace="true"></span>
    <span class="field-validation-valid" data-valmsg-for="Student.HomePhonePrefix" data-valmsg-replace="true"></span>
    <span class="field-validation-valid" data-valmsg-for="Student.HomePhoneLastFour" data-valmsg-replace="true"></span>
    

    这是Student类属性。请注意,学生班级已添加到查看模型中。

    [Digits(ErrorMessage = "Please input only numbers for area code.")]
            [StringLength(3, MinimumLength = 3, ErrorMessage = "Please input 3 numbers for the area code.")]
            public string HomePhoneAreaCode { get; set; }
    
    
            [Digits(ErrorMessage = "Please input only numbers for phone prefix.")]
            [StringLength(3, MinimumLength = 3, ErrorMessage = "Please input 3 numbers for the phone prefix.")]
            public string HomePhonePrefix { get; set; }
    
    
            [Digits(ErrorMessage = "Please input only numbers for phone number.")]
            [StringLength(4, MinimumLength = 4, ErrorMessage = "Please input 4 numbers for the phone number.")]
            [PhoneCodePrefixNumber(FieldOne = "HomePhoneAreaCode", FieldTwo = "HomePhonePrefix", ErrorMessage = "You must enter all three parts of the phone number.")]
            public string HomePhoneLastFour { get; set; }
    

    这是属性代码

    public sealed class PhoneCodePrefixNumberAttribute : ValidationAttribute, IClientValidatable
        {
            public string FieldOne { get; set; }
            public string FieldTwo { get; set; }
    
            protected override ValidationResult IsValid(object value, ValidationContext validationContext)
            {
                var valThis = (IComparable)value;
    
                var baseFieldOneInfo = validationContext.ObjectType.GetProperty(FieldOne);
                var valFieldOne = (IComparable)baseFieldOneInfo.GetValue(validationContext.ObjectInstance, null);
    
                var baseFieldTwoInfo = validationContext.ObjectType.GetProperty(FieldOne);
                var valFieldTwo = (IComparable)baseFieldTwoInfo.GetValue(validationContext.ObjectInstance, null);
    
                ValidationResult result = null;
    
                if (valThis != null || valFieldOne != null || valFieldTwo != null)
                {
                    if (
                        (valThis != null && (valFieldOne == null || valFieldTwo == null)) ||
                        (valFieldOne != null && (valThis == null || valFieldTwo == null)) ||
                        (valFieldTwo != null && (valThis == null || valFieldOne == null))
                        )
                    {
                        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 = "phonecodeprefixnumber";
                compareRule.ValidationParameters.Add("fieldone", FieldOne);
                compareRule.ValidationParameters.Add("fieldtwo", FieldTwo);
                yield return compareRule; 
            }
        }
    

    和客户端验证码

    //PhoneCodePrefixNumber Client Validation Rules
                $.validator.addMethod("phonecodeprefixnumber", function (value, element, params) {
                    // debugger;
                    var fieldone = params.split(",")[0];
                    var fieldtwo = params.split(",")[1];
    
                    if (params == undefined || params == null || params.length == 0 ||
                        value == undefined || value == null || value.length == 0 ||
                        fieldone == undefined || fieldone == null || fieldone.length == 0 ||
                        fieldtwo == undefined || fieldtwo == null || fieldtwo.length == 0){
                        return true;
                    }
    
                    var valueFieldOne = $(fieldone).val();
                    var valueFieldTwo = $(fieldtwo).val();
                    alert(value + "|" + fieldone + "=" + valueFieldOne + "|" + fieldtwo + "=" + valueFieldTwo);
    
                    if (value == "" && valueFieldOne == "" && valueFieldTwo == "")
                        return true;
    
                    if (value == "" || valueFieldOne == "" || valueFieldTwo == "")
                        return false;
    
                    return true;
                });
                $.validator.unobtrusive.adapters.add("phonecodeprefixnumber", ["fieldone", "fieldtwo"], function (options) {
                    options.rules["phonecodeprefixnumber"] = "#" + options.params.fieldone + "," + options.params.fieldtwo;
                    options.messages["phonecodeprefixnumber"] = options.message;
                });
    

1 个答案:

答案 0 :(得分:0)

以下是适用于我的更新属性...

使用

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

<强>正则表达式

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})$

属性代码

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

客户端代码

(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));