如何解决默认正则表达式 django 用于验证电子邮件
最近,我开始玩 Django 并创建了一个用于用户注册的自定义表单。在该表单中创建电子邮件字段我使用类似
email = forms.EmailField()
我观察到诸如 a@a.a 之类的地址被表单视为无效。当然,这是一个无意义的电子邮件地址。尽管如此,我想知道 Django 如何检查有效性。
我在网上找到了一些讨论如何检查电子邮件地址有效性的主题,但所有这些主题都提供了一些自定义方法。找不到有关 django 默认验证器的内容。
使用EmailValidator 来验证给定的值是一个有效的电子邮件地址,使用一个适度复杂的正则表达式。
但是这不是很具体所以我决定在这里问。
解决方法
对于也对此感兴趣的任何人,我建议按照 iklinac 在评论中的友好建议查找实现 (django.core.validators)。
其中不仅有来源,而且还提到了用于派生正则表达式的标准,这些正则表达式检查域和文字是否具有有效格式。
,如果你想检查验证使用像这样的干净函数:
const fs = require('fs');
const fsp = fs.promises;
async function compareFiles(fname1,fname2) {
const kReadSize = 1024 * 8;
let h1,h2;
try {
let openResults = await Promise.allSettled([fsp.open(fname1),fsp.open(fname2)]);
let err;
if (openResults[0].status === "fulfilled") {
h1 = openResults[0].value;
} else {
err = openResults[0].reason;
}
if (openResults[1].status === "fulfilled") {
h2 = openResults[1].value;
} else {
err = openResults[1].reason;
}
// after h1 and h2 are set (so they can be properly closed)
// throw any error we got
if (err) {
throw err;
}
const [stat1,stat2] = await Promise.all([h1.stat(),h2.stat()]);
if (stat1.size !== stat2.size) {
return false;
}
const buf1 = Buffer.alloc(kReadSize);
const buf2 = Buffer.alloc(kReadSize);
let pos = 0;
let remainingSize = stat1.size;
while (remainingSize > 0) {
let readSize = Math.min(kReadSize,remainingSize);
let [r1,r2] = await Promise.all([h1.read(buf1,readSize,pos),h2.read(buf2,pos)]);
if (r1.bytesRead !== readSize || r2.bytesRead !== readSize) {
throw new Error("Failed to read desired number of bytes");
}
if (buf1.compare(buf2,readSize) !== 0) {
return false;
}
remainingSize -= readSize;
pos += readSize;
}
return true;
} finally {
// does not return file close errors
// but does hold resolving the promise until the files are closed
// or had an error trying to close them
// Since we didn't write to the files,a close error would be fairly
// unprecedented unless the disk went down
const closePromises = [];
if (h1) {
closePromises.push(h1.close());
}
if (h2) {
closePromises.push(h2.close());
}
await Promise.allSettled(closePromises);
}
}
compareFiles("temp.bin","temp2.bin").then(result => {
console.log(result);
}).catch(err => {
console.log(err);
});
如果您的电子邮件有效,则此函数返回值,否则返回验证错误
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。