Canonique sans utiliser des cadres avec prototype garniture ajoutée pour les anciens navigateurs
<html>
<head>
<script type="text/javascript">
// add trim to older IEs
if (!String.trim) {
String.prototype.trim = function() {return this.replace(/^\s+|\s+$/g, "");};
}
window.onload=function() { // onobtrusively adding the submit handler
document.getElementById("form1").onsubmit=function() { // needs an ID
var val = this.textField1.value; // 'this' is the form
if (val==null || val.trim()=="") {
alert('Please enter something');
this.textField1.focus();
return false; // cancel submission
}
return true; // allow submit
}
}
</script>
</head>
<body>
<form id="form1">
<input type="text" name="textField1" value="" /><br/>
<input type="submit" />
</form>
</body>
</html>
Voici la version en ligne, mais pas recommandé je montre ici au cas où vous avez besoin d'ajouter la validation sans pouvoir factoriser le code
function validate(theForm) { // passing the form object
var val = theForm.textField1.value;
if (val==null || val.trim()=="") {
alert('Please enter something');
theForm.textField1.focus();
return false; // cancel submission
}
return true; // allow submit
}
passer l'objet de forme en (ce)
<form onsubmit="return validate(this)">
<input type="text" name="textField1" value="" /><br/>
<input type="submit" />
</form>
@mplungjan: ces données sont mises en cache, ont un peu de patience. Il va rattraper dans environ 15 minutes. – BalusC