There are a number of inconsistencies in your code and I will quote them in the course of the answer, let’s start with html, you are doing an action for a file json Is that right? There’s no point in you doing this in view of the JSON receives no requests GET, POST, PUT or DELETE etc... The JSON is like a simple text file for organizing structures, does not issue or receive requests. In view of this you call validaForm 2 times, one inside the input when the user clicks and the other in the submission form, the one of the submission is even acceptable, but the one of the click no input, because whenever the user first clicks this field will be empty. Add a button instead by changing this HTML
let cpfs = '{"dadosUsi":[{"cpf":"400985123"},{"cpf":"400985124"},{"cpf":"400985125"},{"cpf":"400985126"}]}'
function validaForm() {
let cpf = document.getElementById("tx_cpf").value;;
if (cpf.trim().length === 0 ) {
alert("Por favor, CPF invalido.");
}
alert(JSON.parse(cpfs).dadosUsi.filter(i => i.cpf === cpf).length > 0 ? "Já tem cadastro" : "Não tem cadastro")
return false
}
<body id="fundo">
<form action="" method="post" name="dados" onSubmit="return validaForm()" id="paraForm">
<div>
<label for="tx_cpf">CPF:</label>
<input name="tx_cpf" type="text" id="tx_cpf" />
<button>Checa Cpf</button>
</div>
</form>
</body>
Note also that it makes no sense for you to read a file through the client because not always it can be there, not to mention thinking about a system that would be used by other computers, it would be totally meaningless for you to save the data of these users on each client’s computer, this should be done on the server side but I made a demonstration of how it would be possible to check a JSON whether or not there is Cpf, this could be done using the function filter javascript, as its purpose was not defined, I made some changes always returning false in the unsubscribe function, but it is not the best way, you were also checking if Cpf was empty without even having taken the value of it.
Put your function validates form as well
– Anderson Henrique
ready, put the function
– Da11a2
This should be done on the server, not in the browser via js.
– bfavaretto
Php would be better then?
– Da11a2
Whether php would be better or not is already outside the scope, getting into preference languages... So you can use any one that makes the server side, be it Nodejs, PHP etc...
– Anderson Henrique
You can check with Ajax, do not need a form for this, make a request for the json file and see if what is typed in the input already exists in the file.
– LeAndrade