Comments (12)
Obrigado!
Qualquer coisa só chamar!
from datavalidator.
Você quer considerar o vazio { "data_ultima_visita": ""} como válido?
from datavalidator.
Na verdade como o campo é opcional, se vier null tudo ok.
Se vier um valor diferente de null ele tem que ser no tamanho de uma data e também uma data válida.
Quando vem "" ele não pega na validação do isLength e nem na validação da data.
from datavalidator.
Entendi..
A opção "IsOptional" ela deve ser usada pra quando o valor vier nulo ou vazio - e você não quer que ele faça a validação.
A nova opção, vai te dar acesso ao valor do JSONValue, onde você vai dizer para o validador se deve ser opcional ou não.
Faz assim.. Eu vou gerar um release que vai ter uma opção pra ti fazer isso!
.Validate('birthDate')
.Key
.IsRequired.WithMessage('Informe a key ${key}')
.&End
.Value
.Trim
.IsOptional(
function(const AValue: TJSONValue): Boolean
begin
Result := AValue.Null;
end)
.IsJSONString.WithMessage('${key} - ${value} - Não é do tipo string!')
.IsLength(10,10).WithMessage('${key} - Deve ter somente 10 caracteres!')
.IsDate(False).WithMessage('${key} - ${value} - Não é uma data válida!')
.&Not.IsDateGreaterThan(Now, False).WithMessage('${key} - ${value} - A data informada não pode ser maior que a data atual!')
.&Not.IsDateLessThan(IncYear(Now, -90), False).WithMessage('${key} - ${value} - A data informada não pode ser menor que %s', [FormatDateTime('yyyy-mm-dd', IncYear(Now, -90))])
.&End
.&End
from datavalidator.
@giulianon
https://github.com/dliocode/datavalidator/releases/tag/2.0.2
from datavalidator.
Assim já resolve. Aproveitando eu consigo ter esse mesmo esquema ai pra ter um validador customizado tipo:
.Validate('birthDate')
.Key
.IsRequired.WithMessage('Informe a key ${key}')
.&End
.Value
.Trim
.IsOptional(
function(const AValue: TJSONValue): Boolean
begin
Result := AValue.Null;
end)
.CustomValidator(
function(const AValue: TJSONValue): Boolean
begin
// Teste por exemplo se é menor de idade
Result := AValue.GetValue<Integer> < 18;
end)
)
.IsJSONString.WithMessage('${key} - ${value} - Não é do tipo string!')
.IsLength(10,10).WithMessage('${key} - Deve ter somente 10 caracteres!')
.IsDate(False).WithMessage('${key} - ${value} - Não é uma data válida!')
.&Not.IsDateGreaterThan(Now, False).WithMessage('${key} - ${value} - A data informada não pode ser maior que a data atual!')
.&Not.IsDateLessThan(IncYear(Now, -90), False).WithMessage('${key} - ${value} - A data informada não pode ser menor que %s', [FormatDateTime('yyyy-mm-dd', IncYear(Now, -90))])
.&End
.&End
from datavalidator.
Pode usar esse aqui!
.CustomJSONValue(
function(const AValue: TJSONValue): Boolean
begin
end)
from datavalidator.
Lembrando que você pode retornar mensagem personalizadas.
Ex: 1
.CustomJSONValue(
function(const AValue: TJSONValue): Boolean
begin
end)
Ex: 2
.CustomJSONValue(
function(const AValue: TJSONValue; var AMessage: string): Boolean
begin
Result := False;
if AValue.Null then
begin
AMessage := 'Valor é nulo';
Exit;
end;
if not AValue is TJSONNumber then
begin
AMessage := 'Valor deve ser númerico';
Exit;
end;
if AValue.GetValue<Integer> < 18 then
begin
AMessage := 'Valor menor que 18';
Exit;
end;
Result := True;
end)
from datavalidator.
Lembrando que você pode retornar mensagem personalizadas.
Ex: 1
.CustomJSONValue( function(const AValue: TJSONValue): Boolean begin end)Ex: 2
.CustomJSONValue( function(const AValue: TJSONValue; var AMessage: string): Boolean begin Result := False; if AValue.Null then begin AMessage := 'Valor é nulo'; Exit; end; if not AValue is TJSONNumber then begin AMessage := 'Valor deve ser númerico'; Exit; end; if AValue.GetValue<Integer> < 18 then begin AMessage := 'Valor menor que 18'; Exit; end; Result := True; end)
Perfeito.
Sem querer abusar, mais uma então.
Tem alguma forma de e comparar 2 values de um TJSONObject?
Exemplo:
{
"senha":"12345",
"confirmacao_Senha":"123456"
}
.Validate('senha')
.Value
.IsEquals('confirmacao_senha').WithMessage('Senhas não conferem')
.&End
.&End
Isso também encaixaria no .isDateBetween()
from datavalidator.
{
"data_inicio":"2022-01-11",
"data_fim":"2022-01-10"
}
.Validate('dataInicio')
.Value
.IsDateGreaterThan('data_fim').WithMessage('Período inválido')
.&End
.&End
from datavalidator.
Eu faço assim hoje;
function TUsuarioValidator.AlterarSenha(const ABody: TJSONObject): IDataValidatorResult;
begin
Result :=
TDataValidator.JSON(ABody)
.Validate('email')
.Key
.IsRequired.WithMessage('Faltou informar a key "${key}"')
.&End
.Value
.AddSchema(SchemaEmail)
.&End
.&End
.Validate('senha_atual')
.Key
.IsRequired.WithMessage('Faltou informar a key "${key}"')
.&End
.Value
.Trim
.&Not.IsEmpty.WithMessage('Informe a senha atual!')
.IsLength(6, 30).WithMessage('Informe a senha atual de 6 à 30 caracteres!')
.&End
.&End
.Validate('nova_senha')
.Key
.IsRequired.WithMessage('Faltou informar a key "${key}"')
.&End
.Value
.Trim
.&Not.IsEmpty.WithMessage('Informe a nova senha!')
.IsLength(6, 30).WithMessage('Informe a nova senha de 6 à 30 caracteres!')
.CustomValue(
function(const AValue: string; var AMessage: string): Boolean
var
LSenhaAtual: string;
begin
LSenhaAtual := ABody.GetValue<string>('senha_atual');
AMessage := 'A nova senha não pode ser igual a senha atual!';
Result := not AValue.Equals(LSenhaAtual);
if not Result then
Exit;
Result := not LUsuario.CheckPassword(AValue);
end)
.&End
.&End
.Check;
end;
from datavalidator.
Eu faço assim hoje;
function TUsuarioValidator.AlterarSenha(const ABody: TJSONObject): IDataValidatorResult; begin Result := TDataValidator.JSON(ABody) .Validate('email') .Key .IsRequired.WithMessage('Faltou informar a key "${key}"') .&End .Value .AddSchema(SchemaEmail) .&End .&End .Validate('senha_atual') .Key .IsRequired.WithMessage('Faltou informar a key "${key}"') .&End .Value .Trim .&Not.IsEmpty.WithMessage('Informe a senha atual!') .IsLength(6, 30).WithMessage('Informe a senha atual de 6 à 30 caracteres!') .&End .&End .Validate('nova_senha') .Key .IsRequired.WithMessage('Faltou informar a key "${key}"') .&End .Value .Trim .&Not.IsEmpty.WithMessage('Informe a nova senha!') .IsLength(6, 30).WithMessage('Informe a nova senha de 6 à 30 caracteres!') .CustomValue( function(const AValue: string; var AMessage: string): Boolean var LSenhaAtual: string; begin LSenhaAtual := ABody.GetValue<string>('senha_atual'); AMessage := 'A nova senha não pode ser igual a senha atual!'; Result := not AValue.Equals(LSenhaAtual); if not Result then Exit; Result := not LUsuario.CheckPassword(AValue); end) .&End .&End .Check; end;
Entendi. Dessa maneira eu vi que daria pra fazer, mas a dúvida era mais pra saber se ali dentro eu conseguia pegar o valor através de alguma função anônima ou algo do tipo.
Era isso Danilo. Muito obrigado pela atenção e mais uma vez parabéns pelo projeto.
from datavalidator.
Related Issues (2)
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from datavalidator.