场景
效果
实现
打开VS,新建窗体程序
快捷键ctrl+alt+x打开工具箱,拖拽label、TextBox、Button,实现注册窗体布局。
在输入框TextBox后面还有对应的提示用的label,将其Text设为空,设置好name属性,将字体颜色设为红色。
将密码以及确认密码的TextBox的属性--行为--PasswordChar设置为*
在解决资源管理器窗口下右击项目--添加--类
User实体类
User代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RegisterTest
{
class User
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private string pwd;
public string Pwd
{
get { return pwd; }
set { pwd = value; }
}
private string email;
public string Email
{
get { return email; }
set { email = value; }
}
}
}
同理添加Validate验证类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RegisterTest
{
class Validate
{
///验证用户名有效性
///大于4位 第一个字符为字母 且必须包含数字
public Boolean CheckName(string name) {
bool result = false;
char[] chars = name.ToCharArray();
if (name.Length >= 4 && Char.IsLetter(chars[0]))
{
foreach (char c in chars)
{
if(Char.IsDigit(c)){
result = true;
break;
}
}
}
return result;
}
///验证用户密码
///大于6位 且两次输入的密码相同
public Boolean Checkpwd(string pwd1,string pwd2) {
if (pwd1.Length >= 6 && pwd1.Equals(pwd2))
{
return true;
}
else {
return false;
}
}
///验证Email
///必须包含@,在@后面必须包含. 且之间必须有自符
public Boolean CheckEmail(string email) {
if (email.IndexOf('@') != -1 && email.IndexOf('.') > email.IndexOf('@'))
{
return true;
}
else
{
return false;
}
}
}
}
回到页面设计双击注册按钮进入其点击事件的代码编写中
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace RegisterTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Validate validate = new Validate();
bool result = false;
User user = new User();
user.Name = this.username.Text.Trim();
user.Pwd = this.password.Text.Trim();
user.Email = this.email.Text.Trim();
if (!validate.CheckName(user.Name))
{
this.nameMsg.Text = "* 用户名无效";
this.username.Text = "";
}
else if(!validate.Checkpwd(user.Pwd,confirmPassword.Text.Trim()))
{
this.nameMsg.Text = "";
this.pwdMsg.Text = "* 密码无效";
this.password.Text = "";
this.confirmPassword.Text = "";
}
else if (!validate.CheckEmail(user.Email))
{
this.nameMsg.Text = "";
this.pwdMsg.Text = "";
//设置提示框的文本
this.emailMsg.Text = "* 电子邮件无效";
this.email.Text = "";
}
else
{
//将输入框后面的提示框设置为空
this.nameMsg .Text= "";
this.pwdMsg.Text = "";
this.emailMsg.Text="";
result = true;
}
if (result)
{
// \n代表换行 {0} 代表占位符 与后面参数对应
string message = string.Format("用户注册成功! \n 用户名:{0} \n密码:{1}",user.Name,user.Pwd);
//弹窗提示信息
MessageBox.Show(message);
}
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
效果
示例源码下载
https://download.csdn.net/download/badao_liumang_qizhi/11561049