简体   繁体   中英

asp.net mvc 1.0 Validations

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM