简体   繁体   中英

How do i validate my phonumber to start with a 0

i have been trying to create a custom validation using data annotations in mvc. I need to validate that a user enters a phone number that starts with a 0 in a textbox on a view if not they get an error.somehow my logic is wrong im new to coding and having abit of difficulty pls help.

here is my code

     public class FirstNumberAttributes:ValidationAttribute
   {

    public FirstNumberAttributes(int firstdigit)
    {
        _firstdigit = firstdigit;
    }

    protected override ValidationResult isValid(objectvalue,ValidationContext validationContext)           
    {
        if (value!=null)
        {

            var valueAsString = value.ToString();
            if (valueAsString.Substring(0,1)!=_firstdigit)
            {
                return new ValidationResult("Number doesnt start with "+_firstdigit);
            }
         }
        return ValidationResult.Success;
    }
    private readonly int _firstdigit;
}

}

I usually using regular expression to validate phone number. Just use the pattern to what you like to filter it.

String pattern = "[" + _firstNumber + "*]"; 
if(Regex.IsMatch("01234567", pattern)){
    return ValidationResult.Success;
}else{
    return new ValidationResult("Number doesnt start with "+_firstNumber);
}

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