有一种方法可以用TextFormField
或TextField
验证用户的输入,如果不是电子邮件,则拒绝输入。
答案 0 :(得分:6)
您可以为此使用正则表达式
像这样的Form和TextFormField
use std::time::Instant;
const SCREEN_HEIGHT: usize = 1080; //528;
const SCREEN_WIDTH: usize = 1920; //960;
const CHUNK_WIDTH: usize = 256;
const CHUNK_HEIGHT: usize = 256;
const GEN_RANGE: isize = 25; //how far out to gen chunks
fn main() {
let batch_size = 1_000;
struct_test(batch_size);
separate_test(batch_size);
}
fn struct_test(batch_size: u32) {
let world = World::new(CHUNK_WIDTH, CHUNK_HEIGHT, GEN_RANGE); //generate world
let mut screen = vec![vec!([0; 4]; SCREEN_WIDTH); SCREEN_HEIGHT];
let camera_coords: (isize, isize) = (0, 0); //set camera location
let start = Instant::now();
for _ in 0..batch_size {
get_screen(
&mut screen,
&world.data,
camera_coords,
SCREEN_WIDTH,
SCREEN_HEIGHT,
world.chunk_width,
world.chunk_height,
); //gets visible pixels from world as 2d vec
}
println!(
"struct: {:?} {:?}",
start.elapsed(),
start.elapsed() / batch_size
);
}
fn separate_test(batch_size: u32) {
let world = World::new(CHUNK_WIDTH, CHUNK_HEIGHT, GEN_RANGE); //generate world
let cloned_world_data = world.data.clone();
let mut screen = vec![vec!([0; 4]; SCREEN_WIDTH); SCREEN_HEIGHT];
let camera_coords: (isize, isize) = (0, 0); //set camera location
let start = Instant::now();
for _ in 0..batch_size {
get_screen(
&mut screen,
&cloned_world_data,
camera_coords,
SCREEN_WIDTH,
SCREEN_HEIGHT,
CHUNK_WIDTH,
CHUNK_HEIGHT,
); //gets visible pixels from world as 2d vec
}
println!(
"separate: {:?} {:?}",
start.elapsed(),
start.elapsed() / batch_size
);
}
///gets all visible pixels on screen relative camera position in world
#[inline(always)] //INLINE STOPPED WORKING??
pub fn get_screen(
screen: &mut Vec<Vec<[u8; 4]>>,
world: &Vec<Vec<Chunk>>,
camera_coords: (isize, isize),
screen_width: usize,
screen_height: usize,
chunk_width: usize,
chunk_height: usize,
) {
let camera = get_local_coords(&world, camera_coords, chunk_width, chunk_height); //gets loaded coords of camera in loaded chunks
(camera.1 - screen_height as isize / 2..camera.1 + screen_height as isize / 2)
.enumerate()
.for_each(|(py, y)| {
//for screen pixel index and particle in range of camera loaded y
let (cy, ly) = get_local_pair(y, chunk_height); //calculate chunk y and inner y from loaded y
if let Some(c_row) = world.get(cy) {
//if chunk row at loaded chunk y exists
(camera.0 - screen_width as isize / 2..camera.0 + screen_width as isize / 2)
.enumerate()
.for_each(|(px, x)| {
//for screen pixel index and particle in range of camera loaded x
let (cx, lx) = get_local_pair(x, chunk_width); //get loaded chunk x and inner x from loaded x
if let Some(c) = c_row.get(cx) {
screen[py][px] = c.data[ly][lx];
}
//if chunk in row then copy color of target particle in chunk
else {
screen[py][px] = [0; 4]
} //if target chunk doesn't exist color black
})
} else {
screen[py].iter_mut().for_each(|px| *px = [0; 4])
} //if target chunk row doesn't exist color row black
});
}
///calculates local coordinates in world vec from your global position
///returns negative if above/left of rendered area
pub fn get_local_coords(
world: &Vec<Vec<Chunk>>,
coords: (isize, isize),
chunk_width: usize,
chunk_height: usize,
) -> (isize, isize) {
let (wx, wy) = world[0][0].chunk_coords; //gets coords of first chunk in rendered vec
let lx = coords.0 - (wx * chunk_width as isize); //calculates local x coord based off world coords of first chunk
let ly = (wy * chunk_height as isize) - coords.1; //calculates local y coord based off world coords of first chunk
(lx, ly)
}
pub fn get_local_pair(coord: isize, chunk: usize) -> (usize, usize) {
(coord as usize / chunk, coord as usize % chunk)
}
///contains chunk data
#[derive(Clone)]
pub struct Chunk {
//world chunk object
pub chunk_coords: (isize, isize), //chunk coordinates
pub data: Vec<Vec<[u8; 4]>>, //chunk Particle data
}
impl Chunk {
///generates chunk
fn new(chunk_coords: (isize, isize), chunk_width: usize, chunk_height: usize) -> Self {
let data = vec![vec!([0; 4]; chunk_width); chunk_height];
Self { chunk_coords, data }
}
}
pub struct World {
pub data: Vec<Vec<Chunk>>,
pub chunk_width: usize,
pub chunk_height: usize,
}
impl World {
pub fn new(chunk_width: usize, chunk_height: usize, gen_range: isize) -> Self {
let mut data = Vec::new(); //creates empty vec to hold world
for (yi, world_chunk_y) in (gen_range * -1..gen_range + 1).rev().enumerate() {
//for y index, y in gen range counting down
data.push(Vec::new()); //push new row
for world_chunk_x in gen_range * -1..gen_range + 1 {
//for chunk in gen range of row
data[yi].push(Chunk::new(
(world_chunk_x, world_chunk_y),
chunk_width,
chunk_height,
)); //gen new chunk and put it there
}
}
Self {
data,
chunk_width,
chunk_height,
}
}
}
然后验证功能
Form(
autovalidateMode: AutovalidateMode.always,
child: TextFormField(
validator: validateEmail,
),
)
答案 1 :(得分:4)
要验证表单,您可以使用autovalidate
标志并为电子邮件设置验证器。有很多选项,包括正则表达式或手动编写您自己的检查器,但也有一些可用的软件包已经实现了电子邮件检查。
例如https://pub.dev/packages/email_validator。
要使用它,请将其添加到您的pubspec中:
dependencies:
email_validator: '^1.0.0'
import 'package:email_validator/email_validator.dart';
...
Form(
autovalidate: true,
child: TextFormField(
validator: (value) => EmailValidator.validate(value) ? null : "Please enter a valid email",
),
)
还有许多其他验证程序包,其中一些支持的验证类型可能不同。有关更多https://pub.dev/packages?q=email+validation,请参见此搜索。
答案 2 :(得分:0)
TextFormField(
validator: (val) => val.isEmpty || !val.contains("@")
? "enter a valid eamil"
: null,
decoration: InputDecoration(hintText: 'email'),
),
首先,在验证器中,我们检查formfeild是否为空,并且还要检查输入的文本中是否不包含“ @”。如果满足这些条件,则我们将返回文本“输入有效的电子邮件”,否则我们将不返回任何信息
答案 3 :(得分:0)
我建议使用这个名为 validators
的优秀库pubspec.yaml
文件添加依赖项: dependencies:
validators: ^2.0.0 # change to latest version
$ pub get
// on VSCode u need not do anything.
import 'package:validators/validators.dart';
Form(
child: TextFormField(
validator: (val) => !isEmail(val) ? "Invalid Email" : null;,
),
)
答案 4 :(得分:0)
之前的答案都讨论了验证 TextFormField
中的 Form
的选项。问题询问在
TextFormField
或 TextField
TextField
不支持 validator:
命名参数,但您可以使用前面提到的任何技术在用户每次修改电子邮件地址文本时检查电子邮件的有效性。这是一个简单的例子:
TextField(
keyboardType: TextInputType.emailAddress,
textAlign: TextAlign.center,
onChanged: (value) {
setState(() {
_email = value;
_emailOk = EmailValidator.validate(_email);
});
},
decoration:
kTextFieldDecoration.copyWith(hintText: 'Enter your email'),
),
您可以根据需要使用验证结果。一种可能性是在输入有效的电子邮件地址之前保持 login
按钮处于停用状态:
ElevatedButton(
child: Text('Log In'),
// button is disabled until something has been entered in both fields.
onPressed: (_passwordOk && _emailOk) ? ()=> _logInPressed() : null,
),