If you use jQuery, you can create a script more or less like this (I just did it, but you can adjust it to your needs):
(function ($) {
'use strict';
$(function () {
$('form').each(function () {
var $form = $(this);
/**
* Prevenir o popup de requerido default.
*/
$form
.find('[required]')
.removeAttr('required')
.attr('data-required', 'true')
;
$form.on('submit', function (event) {
/**
* Iterar sobre todos os elementos que tenham
* o atributo `required`.
*/
$form
.find('[data-required="true"]')
.each(function () {
var $this = $(this);
/**
* Caso o campo da iteração atual não esteja
* vazio, passe para a próxima iteração.
*/
if ($this.val() !== '') {
$this.removeClass('is-not-valid');
return;
};
/**
* Caso algum campo esteja inválido,
* previna a submissão do formulário.
*/
event.preventDefault();
$this.addClass('is-not-valid');
if (!$this.attr('data-error')) return;
/**
* Criar a mensagem de erro após o campo.
*/
$('<div>', { 'class': 'is-not-valid-error-container' })
.append($('<span>', { 'text': $this.attr('data-error') }))
.insertAfter($this)
;
})
;
});
});
});
}(jQuery));
.is-not-valid {
border-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div>
<label>
Seu nome: <br>
<input type="text" data-error="Qual o seu nome?" required>
</label>
</div>
<div>
<label>
Sua idade: <br>
<input type="number" data-error="Qual a sua idade?" required>
</label>
</div>
<div>
<label>
Seu estado: <br>
<select data-error="Qual o seu estado?" required>
<option value="">Selecione uma opção</option>
<option value="MG">MG</option>
<option value="SP">SP</option>
<option value="RJ">RJ</option>
</select>
</label>
</div>
<div>
<br>
<input type="submit" value="Enviar (ou testar :p)">
</div>
</form>
In theory, the script looks for input
'those with the attribute required
.
If this field is empty, it adds a class (is-not-valid
), and if you have an attribute data-error="Erro que irá aparecer"
, the error will appear after the field.
See how the code works above, and don’t forget to test it. It is worth noting that you can make modifications in order to make it valid for your application.
I also reiterate that for your operation, you will need jQuery in your project (or develop code with the same free idea of this library).
Now it’s up to you! D
The way is to change the code where Alert is implemented, there is no way to replace the native javascript function called
alert()
by a personalized– Alex
If you want to know what each event does: onkeypress is when the key is pressed,
onkeydown
is when the key is pushed downonkeyup
is when the key goes up.onblur
the user takes the input focus of a certain form,onfocus
is when the input of a form is "clicked"/focused. Just to guide you– Alex
Primefaces accepts this change?
– Sam
@dvd accepts. In case my question now is just like showing up an explanatory message when hovering the mouse or clicking the input.
– Luan Silva