 |
Club Builder Foro de C++Builder en español
|
| Ver tema anterior :: Ver tema siguiente |
| Autor |
Mensaje |
Isa1976 Lt Cmdr


Registrado: 23 Nov 2005Mensajes: 104
|
Publicado: Lun 09 Jul, 2007 6:37 pm Asunto: Verificar que una direccion de email es correcta |
|
|
Hola!
estoy intentando hacer una función que me diga si una direccion de email es buena o mala.
El problema es que una dirección de email puede tener muchas variantes.
Por ejemplo: "Isa...bel"@[23.112.233.5] es una dirección legal, rara, pero legal.
En este link http://www.ietf.org/rfc/rfc0822.txt, encontramos el estandard RFC822 que habla (demasiado...) sobre este tema.
Buscando por ahí encontré esto...
| Código: | /* The following is the list of known TLDs that an e-mail address must end with. */
var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
/* The following pattern is used to check if the entered e-mail address
fits the user@domain format. It also is used to separate the username
from the domain. */
var emailPat=/^(.+)@(.+)$/;
/* The following string represents the pattern for matching all special
characters. We don't want to allow special characters in the address.
These characters include ( ) < > @ , ; : \ " . [ ] */
var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
/* The following string represents the range of characters allowed in a
username or domainname. It really states which chars aren't allowed.*/
var validChars="\[^\\s" + specialChars + "\]";
/* The following pattern applies if the "user" is a quoted string (in
which case, there are no rules about which characters are allowed
and which aren't; anything goes). E.g. "jiminy cricket"@disney.com
is a legal e-mail address. */
var quotedUser="(\"[^\"]*\")";
/* The following pattern applies for domains that are IP addresses,
rather than symbolic names. E.g. joe@[123.124.233.4] is a legal
e-mail address. NOTE: The square brackets are required. */
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
/* The following string represents an atom (basically a series of non-special characters.) */
var atom=validChars + '+';
/* The following string represents one word in the typical username.
For example, in john....@somewhere.com, john and doe are words.
Basically, a word is either an atom or quoted string. */
var word="(" + atom + "|" + quotedUser + ")";
// The following pattern describes the structure of the user
var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
/* The following pattern describes the structure of a normal symbolic
domain, as opposed to ipDomainPat, shown above. */
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
/* Finally, let's start trying to figure out if the supplied address is valid. */
/* Begin with the coarse pattern to simply break up user@domain into
different pieces that are easy to analyze. */
var matchArray=emailStr.match(emailPat);
if (matchArray==null) {
/* Too many/few @'s or something; basically, this address doesn't
even fit the general mould of a valid e-mail address. */
alert("Email address seems incorrect (check @ and .'s)");
return false;
}
var user=matchArray[1];
var domain=matchArray[2];
// Start by checking that only basic ASCII characters are in the strings (0-127).
for (i=0; i<user.length; i++) {
if (user.charCodeAt(i)>127) {
alert("Ths username contains invalid characters.");
return false;
}
}
for (i=0; i<domain.length; i++) {
if (domain.charCodeAt(i)>127) {
alert("Ths domain name contains invalid characters.");
return false;
}
}
// See if "user" is valid
if (user.match(userPat)==null) {
// user is not valid
alert("The username doesn't seem to be valid.");
return false;
}
/* if the e-mail address is at an IP address (as opposed to a symbolic
host name) make sure the IP address is valid. */
var IPArray=domain.match(ipDomainPat);
if (IPArray!=null) {
// this is an IP address
for (var i=1;i<=4;i++) {
if (IPArray[i]>255) {
alert("Destination IP address is invalid!");
return false;
}
}
return true;
}
// Domain is symbolic name. Check if it's valid.
var atomPat=new RegExp("^" + atom + "$");
var domArr=domain.split(".");
var len=domArr.length;
for (i=0;i<len;i++) {
if (domArr[i].search(atomPat)==-1) {
alert("The domain name does not seem to be valid.");
return false;
}
}
/* domain name seems valid, but now make sure that it ends in a
known top-level domain (like com, edu, gov) or a two-letter word,
representing country (uk, nl), and that there's a hostname preceding
the domain or country. */
if (checkTLD && domArr[domArr.length-1].length!=2 &&
domArr[domArr.length-1].search(knownDomsPat)==-1) {
alert("The address must end in a well-known domain or two letter " + "country.");
return false;
}
// Make sure there's a host name preceding the domain.
if (len<2)
{
return false;
}
// If we've gotten this far, everything's valid!
return true;
|
Mas o menos puedo entenderlo, pero las máscaras no se como tratarlas, pero... como paso yo esto a c++?:
var emailPat=/^(.+)@(.+)$/;
var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
var validChars="\[^\\s" + specialChars + "\]";
Otra cosa, la funcion "match" que pone en el codigo no la encuentro, | Código: | // See if "user" is valid
if (user.match(userPat)==null) {... | en su lugar he encontrado esta: MatchesMask
| Código: | /*String emailPat="/^(.+)@(.+)$/";
if (MatchesMask(Edit1->Text,emailPat)) |
MUCHAS GRACIAS! |
|
| Volver arriba |
|
 |
Isa1976 Lt Cmdr


Registrado: 23 Nov 2005Mensajes: 104
|
Publicado: Lun 09 Jul, 2007 9:15 pm Asunto: Aclaraciones |
|
|
He estado buscando bastante... (ya me duele la cabeza y todo), y al final he confeccionado una lista que podría ser muy util para alguien, son los caracteres permitidos en el nombre local de una direccion email:
OK: + - . ... 0-9 A-Z a-z _
NO: espacio ! ( ) < > @ , ; : \ " . [ ] * # % $ ` |
podria ser: & ' * / = ? ^ { } ~
Muchas gracias! |
|
| Volver arriba |
|
 |
_Leo Site Admin

Registrado: 11 Ago 2002Mensajes: 1875Ubicación: Lanzarote - Islas Canarias (España)
|
Publicado: Mar 10 Jul, 2007 1:59 am Asunto: |
|
|
| Isa1976 escribió: | | Otra cosa, la funcion "match" que pone en el codigo no la encuentro, |
No la encuentras porque el código que has puesto esta en JavaScript y esa función no existe ni en la librería estándar de C ni de C++..
| Isa1976 escribió: | | en su lugar he encontrado esta: MatchesMask |
No tiene nada que ver, está pensada principalmente para nombres de archivos, te permitirá usar "*" y "?" principalmente.
He convertido el código intentando no cambiarlo mucho. He añadido un par de funciones que hacen más o menos lo que "match" y "split" en JavaScript, espero que te sirva:
| Código: | //---------------------------------------------------------------------------
// Cabeceras necesarias
//---------------------------------------------------------------------------
#include <pcreposi.h>
#include <memory>
//---------------------------------------------------------------------------
// Funciones utilizadas en IsValidEmail()
//---------------------------------------------------------------------------
// Para entender mejor lo que hace esta función:
// http://en.wikipedia.org/wiki/PCRE
void RegExpMatch(String strIn, String mask, TStrings* slOut)
{
slOut->Clear();
regex_t regex;
regcomp(®ex, mask.c_str(), 0);
regmatch_t match[10];
int ret = regexec(®ex, strIn.c_str(), 10, match, 0);
if (ret != REG_NOMATCH)
{
for (int i=0; i<10; i++)
{
regmatch_t& m = match[i];
String str = strIn.SubString(m.rm_so + 1, m.rm_eo - m.rm_so).Trim();
if (!str.IsEmpty())
slOut->Append(str);
}
}
regfree(®ex);
}
void Split(String strIn, String separador, TStrings* slOut)
{
slOut->Clear();
strIn.Unique();
char* p = strtok(strIn.c_str(), separador.c_str());
while (p)
{
slOut->Append(p);
p = strtok(0, separador.c_str());
}
}
//---------------------------------------------------------------------------
// Función principal. Devuelve true si el eMail es valido
//---------------------------------------------------------------------------
bool IsValidEmail(String emailStr, bool checkTLD = true)
{
/* The following is the list of known TLDs that an e-mail address must end with. */
String knownDomsPat = "^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$";
/* The following pattern is used to check if the entered e-mail address
fits the user@domain format. It also is used to separate the username
from the domain. */
String emailPat = "^(.+)@(.+)$";
/* The following string represents the pattern for matching all special
characters. We don't want to allow special characters in the address.
These characters include ( ) < > @ , ; : \ " . [ ] */
String specialChars = "\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
/* The following string represents the range of characters allowed in a
username or domainname. It really states which chars aren't allowed.*/
String validChars = "\[^\\s" + specialChars + "\]";
/* The following pattern applies if the "user" is a quoted string (in
which case, there are no rules about which characters are allowed
and which aren't; anything goes). E.g. "jiminy cricket"@disney.com
is a legal e-mail address. */
String quotedUser = "(\"[^\"]*\")";
/* The following pattern applies for domains that are IP addresses,
rather than symbolic names. E.g. joe@[123.124.233.4] is a legal
e-mail address. NOTE: The square brackets are required. */
String ipDomainPat = "^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$";
/* The following string represents an atom (basically a series of non-special characters.) */
String atom = validChars + "+";
/* The following string represents one word in the typical username.
For example, in john....@somewhere.com, john and doe are words.
Basically, a word is either an atom or quoted string. */
String word= "(" + atom + "|" + quotedUser + ")";
// The following pattern describes the structure of the user
String userPat = "^" + word + "(\\." + word + ")*$";
/* The following pattern describes the structure of a normal symbolic
domain, as opposed to ipDomainPat, shown above. */
String domainPat = "^" + atom + "(\\." + atom +")*$";
/* Finally, let's start trying to figure out if the supplied address is valid. */
/* Begin with the coarse pattern to simply break up user@domain into
different pieces that are easy to analyze. */
std::auto_ptr<TStringList> matchArray(new TStringList);
RegExpMatch(emailStr, emailPat, matchArray.get());
if (!matchArray->Count) {
/* Too many/few @'s or something; basically, this address doesn't
even fit the general mould of a valid e-mail address. */
ShowMessage("Email address seems incorrect (check @ and .'s)");
return false;
}
String user = matchArray->Strings[1];
String domain = matchArray->Strings[2];
// Start by checking that only basic ASCII characters are in the strings (0-127).
for (int i = 1; i <= user.Length(); i++) {
if ((UCHAR)user[i] > 127) {
ShowMessage("Ths username contains invalid characters.");
return false;
}
}
for (int i = 1; i <= domain.Length(); i++) {
if ((UCHAR)domain[i] > 127) {
ShowMessage("Ths domain name contains invalid characters.");
return false;
}
}
// See if "user" is valid
RegExpMatch(user, userPat, matchArray.get());
if (!matchArray->Count) {
// user is not valid
ShowMessage("The username doesn't seem to be valid.");
return false;
}
/* if the e-mail address is at an IP address (as opposed to a symbolic
host name) make sure the IP address is valid. */
std::auto_ptr<TStringList> ipArray(new TStringList);
RegExpMatch(domain, ipDomainPat, ipArray.get());
if (ipArray->Count) {
// this is an IP address
for (int i = 0; i < 4; i++) {
if (ipArray->Strings[i].ToIntDef(256) > 255) {
ShowMessage("Destination IP address is invalid!");
return false;
}
}
return true;
}
// Domain is symbolic name. Check if it's valid.
String atomPat = "^" + atom + "$";
std::auto_ptr<TStringList> domArr(new TStringList);
Split(domain, ".", domArr.get());
int len = domArr->Count;
for (int i = 0; i < len; i++) {
RegExpMatch(domArr->Strings[i], atomPat, matchArray.get());
if (!domArr->Count) {
ShowMessage("The domain name does not seem to be valid.");
return false;
}
}
/* domain name seems valid, but now make sure that it ends in a
known top-level domain (like com, edu, gov) or a two-letter word,
representing country (uk, nl), and that there's a hostname preceding
the domain or country. */
if (checkTLD) {
RegExpMatch(domArr->Strings[len-1], knownDomsPat, matchArray.get());
if (domArr->Strings[len-1].Length() != 2 && !matchArray->Count) {
ShowMessage("The address must end in a well-known domain or two letter + country.");
return false;
}
}
// Make sure there's a host name preceding the domain.
if (len < 2)
return false;
// If we've gotten this far, everything's valid!
return true;
} |
Un pequeño ejemplo de uso:
| Código: | String email = "prueba@dominio.com";
ShowMessage( IsValidEmail(email) ? "Valido":"NO valido" ); |
|
|
| Volver arriba |
|
 |
Angel Master


Registrado: 15 Abr 2003Mensajes: 2311Ubicación: Toledo (España)
|
|
| Volver arriba |
|
 |
Isa1976 Lt Cmdr


Registrado: 23 Nov 2005Mensajes: 104
|
Publicado: Mar 10 Jul, 2007 9:11 am Asunto: |
|
|
Hooola!
me parece demasiado lo que has hecho, casi me ha dado vergüenza copiar el código ; )
La verdad es que has hecho una función muy interesante para todos.
MUCHAS GRACIAS! |
|
| Volver arriba |
|
 |
ifrit Master


Registrado: 12 Jun 2007Mensajes: 509Ubicación: La Habana, Cuba
|
Publicado: Dom 11 Ene, 2009 11:33 am Asunto: |
|
|
_Leo hasta hoy tambien utilizaba esta funcion para bcb6 pero ahora en el bcb2009 no me funciona , ningun error pero me valida de falsa las cuentas de correo , que puede ser ? _________________ Todos somos ignorantes, lo que no todos ignoramos lo mismo... |
|
| Volver arriba |
|
 |
_Leo Site Admin

Registrado: 11 Ago 2002Mensajes: 1875Ubicación: Lanzarote - Islas Canarias (España)
|
Publicado: Dom 11 Ene, 2009 11:24 pm Asunto: |
|
|
| ifrit escribió: | | ahora en el bcb2009 no me funciona , ningun error pero me valida de falsa las cuentas |
No te da ningun error porque seguramente no tienes el Update1 instalado, ya que lo correcto es que te diese unos cuantos errores...
En este caso esas funciones internamente trabajan con Ansi, por lo tanto cambia todos los parametros de las 3 funciones "String" por "AnsiString" y funcionara en todas las versiones. O sea:
Cambia: void RegExpMatch(String strIn, String mask, TStrings* slOut)
Por: void RegExpMatch(AnsiString strIn, AnsiString mask, TStrings* slOut)
void Split(String strIn, String separador, TStrings* slOut)
Por: void Split(AnsiString strIn, AnsiString separador, TStrings* slOut)
bool IsValidEmail(String emailStr, bool checkTLD = true)
Por: bool IsValidEmail(AnsiString emailStr, bool checkTLD = true) |
|
| Volver arriba |
|
 |
ifrit Master


Registrado: 12 Jun 2007Mensajes: 509Ubicación: La Habana, Cuba
|
Publicado: Dom 11 Ene, 2009 11:46 pm Asunto: |
|
|
Correo editado
_Leo mala mia habia hecho otros cambios tambien y por eso no funcionaba con lo que me dices es correcto 100% gracias y perdona la respuesta apresurada , no me acoradaba de los otros cambios que habia echo _________________ Todos somos ignorantes, lo que no todos ignoramos lo mismo...
Ultima edición por ifrit el Lun 12 Ene, 2009 12:02 am, editado 1 vez |
|
| Volver arriba |
|
 |
_Leo Site Admin

Registrado: 11 Ago 2002Mensajes: 1875Ubicación: Lanzarote - Islas Canarias (España)
|
Publicado: Dom 11 Ene, 2009 11:52 pm Asunto: |
|
|
| Pues lo siento, cambiando SOLO las 3 líneas que te he dicho a mi me funciona correctamente. A ver si alguien mas lo prueba y nos comenta que tal le va. (Tengo instalados el Update1+Update2) |
|
| Volver arriba |
|
 |
grz47 Ens


Registrado: 05 Ago 2005Mensajes: 40Ubicación: SINALOA, MEXICO
|
Publicado: Jue 02 Feb, 2012 3:22 am Asunto: gracias _leo eres un master |
|
|
para que funcione con rad studio 2010 y win 7 solo hice el cambio a AnsiString y funciono perfecto.
gracias _________________ GRZ 47 |
|
| Volver arriba |
|
 |
|
|
No puedes publicar temas nuevos en este foro No puedes responder a temas en este foro No puedes editar tus mensajes en este foro No puedes borrar tus mensajes en este foro No puedes votar en las encuestas de este foro
|
© 2002–2026 Club Builder · Funciona con phpBB.
|