Forum Xamarin.Forms

Announcement:

The Xamarin Forums have officially moved to the new Microsoft Q&A experience. Microsoft Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

To create new threads and ask questions head over to Microsoft Q&A for .NET and get involved today.

Validation for Entry

Hi Techie,
How to add the validation for Entry. Validation for Email, Password, Phone number , Etc.

Thanks in Advance,
Vasanth

Answers

  • LeonLuLeonLu Member, Xamarin Team Xamurai

    You can refer to the following link to validate for Entry, we can use Regex to validate

    https://docs.microsoft.com/en-us/xamarin/xamarin-forms/enterprise-application-patterns/validation#specifying-validation-rules

    For example. validating email addresses we can create anEmailRule:

    public class EmailRule<T> : IValidationRule<T>  
    {  
        public string ValidationMessage { get; set; }  
    
        public bool Check(T value)  
        {  
            if (value == null)  
            {  
                return false;  
            }  
    
            var str = value as string;  
            Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");  
            Match match = regex.Match(str);  
    
            return match.Success;  
        }  
    }
    

    Phone Number you can try to following Regex:

    ^\+?(\d[\d-. ]+)?(\([\d-. ]+\))?[\d-. ]+\d$
    
  • JohnHardmanJohnHardman GBUniversity admin
    edited November 2020

    @Vasanthakumar06

    The Enterprise patterns e-book that @LeonLu linked to above is the place to start when it comes to putting together decent validation in Xamarin.Forms . Note, however, that the implementation can be improved. The way that it is presented in that e-book forces your ViewModel to reference Xamarin.Forms. Your View should do that, not your ViewModel. Also, if you are implementing MVVM strictly, you may prefer to have your validation rules driven from your Model layer, not the ViewModel. It doesn't take many changes to get that Enterprise patterns code to do handle these things correctly, but it takes some effort to sort it out. Hopefully, if that e-book is updated, either for Xamarin.Forms or MAUI, the code will be updated too.

    Remember too, that whatever validation system you choose to use, you may need validation messages to appear in different languages for different users (which isn't always as simple as just have a different set of strings in your resources), and you may need different messages for users of accessibility options/devices (e.g. what a Screen Reader reads aloud to a visually impaired user may want to be different text to what you would display on the screen).

    cc. @DavidBritch

  • LeonLuLeonLu Member, Xamarin Team Xamurai

    @Vasanthakumar06 Are there any update for this issue, please reply is helpful, please click the Yes tab under the helpful answer.

Sign In or Register to comment.