NEWS

[DEVEXPRESS] Hướng dẫn Validate Form sử dụng adornerUIManager và DataAnnotations C#

[DEVEXPRESS] Hướng dẫn Validate Form sử dụng adornerUIManager và  DataAnnotations C#
Đăng bởi: Thảo Meo - Lượt xem: 12789 13:55:36, 21/12/2019DEVEXPRESS   In bài viết

Xin chào các bạn, bài viết hôm nay mình sẽ tiếp tục hướng dẫn các bạn cách Validate Form trong lập trình Winform C# sử dụng bộ công cụ Devexpress.

Trong lập trình ứng dụng, website hay bất kỳ ngôn ngữ thiết kế Form nào.

Khi chúng ta tạo Form submit, thì trước khi submit chúng ta phải kiểm tra người dùng nhập dữ liệu vào có đúng khuôn mẫu của mình hay không.

validate_form_devexpress_csharp

Mình có thể tạo ra một template để người dùng nhập vào.

Ở ví dụ dưới đây mình sẽ demo cách kiểm tra validate form Customer.

Bao gồm các thông tin validate sau:

+ name, username, password, age (Required - bắt buộc phải nhập)

+ password nhập vào tối đa phải 8 ký tự 

+ age Tuổi chỉ được nhập số trong khoảng cho phép của mình (18 - 60)

+ email phải nhập theo chuẩn emailname@domainname.com

+ Điện thoại phải nhập theo chuẩn điện thoại của quốc gia mình. Ví dụ: ở Việt Nam +(84)933.913.122

Dưới đây là hình ảnh demo ứng dụng Validate Form nhập liệu Customer của mình:

validate_form_devexpress

Đầu tiên mình tạo một class Customer.cs và sử dụng DataAnnotations C#:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace validateForm
{
    class Customer
    {
      
            public Customer() { }

            [Required(ErrorMessage = "This field is required.")]
            public string Name
            {
                get;
                set;
            }
            [Required(ErrorMessage = "This field is required.")]
            public string UserName
            {
                get;
                set;
            }
            [DataType(DataType.Password, ErrorMessage = "Invalid password.")]
            [Required(ErrorMessage = "This field is required.")]
            public string Password
            {
                get;
                set;
            }
            [Range(20, 120, ErrorMessage = "Enter the age between 20 and 100.")]
            public int Age
            {
                get;
                set;
            }
            [Required(ErrorMessage = "This field is required.")]
            public string EMail
            {
                get;
                set;
            }
            public string Phone
            {
                get;
                set;
            }
            public string Address
            {
                get;
                set;
            }
       
    }
}

Và dưới đây là source code cho Form1.cs Validate Form C#:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.Utils.VisualEffects;
using DevExpress.XtraTab;

namespace validateForm
{
    public partial class Form1 : DevExpress.XtraEditors.XtraForm
    {
        public Form1()
        {
            InitializeComponent();
            this.CausesValidation = false;
            this.AutoValidate = AutoValidate.EnableAllowFocusChange;
            tePassword.Validating += OnPasswordValidating;
            tePhone.Validating += OnPhoneValidating;
            teAge.Validating += OnAgeValidating;
            teName.Tag = vhName;
            teUserName.Tag = vhUserName;
            tePassword.Tag = vhPassword;
            teAddress.Tag = vhAddress;
            teAge.Tag = vhAge;
            teEMail.Tag = vhEMail;
            tePhone.Tag = vhPhone;
        }
        void OnAgeValidating(object sender, CancelEventArgs e)
        {
            vhAge.Properties.State = CalcTextEditValidationState(teAge, e);
        }
        ValidationHintState CalcTextEditValidationState(DevExpress.XtraEditors.TextEdit edit, CancelEventArgs e)
        {
            if (edit.EditValue == null || string.IsNullOrEmpty(edit.Text))
                return ValidationHintState.Indeterminate;
            return e.Cancel ? ValidationHintState.Invalid : ValidationHintState.Valid;
        }
        void OnPhoneValidating(object sender, CancelEventArgs e)
        {
            vhPhone.Properties.State = CalcTextEditValidationState(tePhone, e);
        }
        void OnCheckButtonClick(object sender, EventArgs e)
        {
            dataLayoutControl.ValidateChildren();
        }
        void OnInvalidValue(object sender, DevExpress.XtraEditors.Controls.InvalidValueExceptionEventArgs e)
        {
            Control editor = sender as Control;
            if (editor == null) return;
            if (editor == tePassword)
                OnInvalidPasswordValue(e);
            if (editor == teEMail)
                OnInvalidEMailValue(e);
            if (editor == tePhone)
                OnInvalidPhoneValue(e);
            ValidationHint hint = editor.Tag as ValidationHint;
            if (hint != null)
            {
                hint.Properties.InvalidState.Text = e.ErrorText;
                e.ErrorText = null;
            }
        }
        void OnPasswordValidating(object sender, CancelEventArgs e)
        {
            if (tePassword.EditValue != null && tePassword.EditValue.ToString().Length < 8)
                e.Cancel = true;
        }
        void OnInvalidPhoneValue(DevExpress.XtraEditors.Controls.InvalidValueExceptionEventArgs e)
        {
            if (e.ErrorText == "Invalid Value")
                e.ErrorText = "Invalid phone number.";
        }
        void OnInvalidEMailValue(DevExpress.XtraEditors.Controls.InvalidValueExceptionEventArgs e)
        {
            if (e.ErrorText == "Invalid Value")
                e.ErrorText = "Invalid e-mail.";
        }
        void OnInvalidPasswordValue(DevExpress.XtraEditors.Controls.InvalidValueExceptionEventArgs e)
        {
            if (e.ErrorText == "Invalid Value")
                e.ErrorText = "Your password must be at least 8 characters.";
        }
    }
}

Các bạn có thể download source code bên dưới về để tham khảo nhé.

Chúc các bạn thành công!

Thanks for Watching.

 

DOWNLOAD SOURCE

 

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[DEVEXPRESS] Hướng dẫn Validate Form sử dụng adornerUIManager và  DataAnnotations C#
Đăng bởi: Thảo Meo - Lượt xem: 12789 13:55:36, 21/12/2019DEVEXPRESS   In bài viết

CÁC BÀI CÙNG CHỦ ĐỀ

Đọc tiếp
.