C#中关于用户名和密码的验证问题

猪小花1号2018-08-28 15:10


本次练习的目的是使用LinQ to XML,正则表达式,明天在这个基础上练习使用序列化和反序列化,继续加点儿小功能。

首先,这是一个窗体程序,设计如下:

存放用户名和密码的XML如下:

实现的代码如下:

1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10 using System.Text.RegularExpressions;
11 using System.Xml;
12 using System.Xml.Linq;
13
14 namespace CheckInfo
15 {
16 public partial class Form1 : Form
17 {
18 public Form1()
19 {
20 InitializeComponent();
21 }
22
23 private void textBox1_TextChanged(object sender, EventArgs e)
24 {
25 if (textBox1.Text == "请输入用户名,格式:qarootdc\\jqhuang")
26 {
27 textBox1.Text = "";
28 }
29
30 }
31
32 private void textBox2_TextChanged_1(object sender, EventArgs e)
33 {
34 if (textBox2.Text == "请输入密码")
35 {
36 textBox2.Text = "";
37 }
38 }
39
40 private void button1_Click(object sender, EventArgs e)
41 {
42 if (isValidUserName(textBox1.Text) == false)
43 {
44 MessageBox.Show("用户名格式不正确!请重新输入!");
45 textBox1.Text = "";
46 }
47 else
48 {
49 //用户名格式正确.
50 CheckUserAndPwd(textBox1.Text,textBox2.Text);
51 }
52 }
53
54 private void CheckUserAndPwd(string username, string pwd)
55 {
56 //读取UserInfo.xml检测user是否存在
57 XDocument userInfo = XDocument.Load(@"C:\Users\jqhuang\Desktop\UserInfo.xml");
58 var result = from userElement in userInfo.Element("System").Element("users").Elements() where userElement.Element("username").Value.ToString() == textBox1.Text.ToString() select userElement.Element("pwd").Value;
59 if (result != null)
60 {
61 foreach (var password in result)
62 {
63 if (password == pwd)
64 {
65 MessageBox.Show("用户名和密码匹配成功!");
66 }
67 else
68 {
69 MessageBox.Show("用户名和密码不匹配,请重新输入密码");
70 textBox2.Text = "";
71 }
72 }
73 }
74 else
75 {
76 MessageBox.Show("您输入的用户不存在!");
77 }
78 }
79
80 bool isValidUserName(string userName)
81 {
82 return Regex.IsMatch(userName,@"^.+\\.+$");
83 }
84 }
85 }


运行效果图如下——

1、用户名不存在的情况:

/

 

2、用户名和密码不匹配的情况:

 

3、用户名格式不正确的情况(用正则表达式验证):

 

4、用户名和密码匹配成功的情况:

 


网易云新用户大礼包:https://www.163yun.com/gift

本文来自博客园天外云归专栏,经作者蓝天祐授权发布。