views:

13

answers:

1

Im working in asp.net mvc application which was done in mvc 1... so validations were done following the nerd dinner 1.0 tutorial

I just defined a rule like this

public bool Is_CellPhone(string val)        
        {
            Regex celular = new Regex("^04[12][246][0-9]{7}$");
            return celular.IsMatch(val);
        }

and in my GetRuleValidations I do this

    if (!Is_CellPhone(Celular))
                    yield return new RuleViolation("El celular no cumple el formato", 

"Celular");

The problem is.. cell phone is not required so when the user doesnt submit that value the validation method runs anyway and returns an error because of the null string... what can I do to properly prevent this error?

+1  A: 

Just return true if the string is null or empty:

public bool Is_CellPhone(string val)        
        {
            if (string.IsNullOrEmpty(val)) { return true; }
            Regex celular = new Regex("^04[12][246][0-9]{7}$");
            return celular.IsMatch(val);
        }

I suspect you can also cover this in the regular expression, but I suck at regex so I won't pretend to give advice there.

Wyatt Barnett
I guess that works but then you would need to do that for every custom rule... which is kind of pointless.. rule validations should only run when the value was submitted
NachoF