Validating a value within a string

Topics: Validation Application Block
Sep 20, 2011 at 4:26 PM
        [RegexValidator(@"^Q+[0-9]*$", MessageTemplate="Carton quantity must start with 'Q'")]
        [RangeValidator(1, RangeBoundaryType.Inclusive, 64000, RangeBoundaryType.Inclusive, MessageTemplate="Carton quantity must be between 1 and 64000")]
        public int CartonQuantity {get; set;}
How should I accomplish the above?  First, CartonQuantity will need to be a string, but how can I validate that it does start with 'Q' and the remainder is a value between 1 and 64000?
Sep 21, 2011 at 2:54 AM


My idea here is to split your RegexValidator into two basically creating two seperate RegexValidator that would validate each conditions. Hope this helps.


Noel Angelo Bolasoc
Avanade Software
Avanade, Inc.
Contact Us

Sep 21, 2011 at 3:14 AM


I started looking into SelfValidators.  Is that a possibility on a WCF DataContract?

Sep 21, 2011 at 3:55 AM

Though I haven't tried it yet, I'm positive that it will work on WCF.


Noel Angelo Bolasoc
Avanade Software
Avanade, Inc.
Contact Us

Sep 21, 2011 at 2:32 PM

SelfValidation is working great.  I would still prefer two RegExes though.  Thanks..


        public void Validate(ValidationResults results)
            /**** CartonQuantity Validation ****/
            // starts with Q ?
            RegexValidator regExValidator = new RegexValidator(@"^Q+[0-9]*$", "Carton quantity must start with 'Q'");
            regExValidator.DoValidate(CartonQuantity, this, "CartonQuantity", results);
            // followed by a number between 1 and 64000 ?
            int intResult = 0;
            bool isInt = int.TryParse(CartonQuantity.Substring(1, CartonQuantity.Length-1), out intResult);

            if (!isInt) 
                results.AddResult(new ValidationResult("Value cannot be converted to an integer.", this, "CartonQuantity","", null));
                RangeValidator rangeValidator = new RangeValidator(1, RangeBoundaryType.Inclusive, 64000, RangeBoundaryType.Inclusive,"Carton quantity must be between 1 and 64000");
                rangeValidator.DoValidate(intResult, this, "CartonQuantity", results);