Data type checking with xVal

I am trying to find the best way to validate data in an MVC C # application and xVal seems to be the best fit. However, I ran into a data validation issue.

First I did the UpdateModel on the DTO and then did the check on the DTO. This works great for things like required fields, however UpdateModel throws an exception if you try, for example, to match a string ("asd") to a decimal field. Since the UpdateModel had to be fired before there was data to check, I was not sure how to get around this.

My solution was to create a DTO for each form that UpdateModel will update, run validation on it, and then copy the values ​​into the corresponding DTOs. All the attributes in the DTO form would be strings, so the UpdateModel will never fail and I would provide data validation via xVal. However, even though rules like mandatory kick in, I can't get the DataType rule to use (try DataType.Currency in this case).

I also tried to get client side validation to work, but I was hoping there was a clean server side validation of datatypes.

What have others been doing regarding server side data type checking?

+2


source to share


2 answers


As a result, I created several DTOs that represent forms. These DTOs will accept Request.Form and automatically map all form values ​​to internal properties (ex public string email, public string firstname) based on which they have the same name as the form values.

They will have all string properties and I would put xVal attributes on them. I then used xVal and regular expressions to make sure the data took effect (from a valid date, email, number, etc.). This way, there will never be an exception, because it always fits into a string, not in .Net trying to parse it to a date or something.



This will make sure the data always did it in xVal where I could do the validation I want and then convert to the appropriate type like DateTime once I know I have valid data.

+2


source


I am using custom validators derived from ValidationAttribute to validate data to be parsed server side from string to other data types. For example:

public class DateAttribute : ValidationAttribute
    {

        public override bool IsValid(object value)
        {
            var date = (string)value;
            DateTime result;
            return DateTime.TryParse(date, out result);
        }
    }

      



I also found a way to include such validation attributes in client-side and server-side validation attributes without writing any custom JavaScript code. I just have to get from another base class of the validation attribute. Take a look at my article on client side validation if you'd like to learn more about it.

+1


source







All Articles