简体   繁体   中英

Javascript-Jquery form

I develop a basic form in HTML/JS. I use javascript to check my fields. But they are only verifying when they are empty. How do I validate my form if the fields are correct or invalid if the fields are incorrect.

Maybe i need to complete my verifier function(). But how ? I am a little lost ;(

Thank you in advance !

JS :

 var regex = /[^a-zA-Z]/; var regex2 = /[^a-zA-Z_]/; $(document).ready(function () { var $nom = $('#name'), $prenom = $('#prenom'), $centre = $('#centre'), $magasin = $('#magasin'), $profil = $('#profil'), $date = $('#date'), $envoie = $('#envoie'), $erreur = $('#erreur'), $champ = $('.champ'); /* FONCTION REGEX */ $nom.keypress(function() { var color = regex.test(this.value) ? "red" : "green"; $(this).css({ borderColor: color, color: color }); }); $prenom.keypress(function() { var color = regex.test(this.value) ? "red" : "green"; $(this).css({ borderColor: color, color: color }); }); $profil.keypress(function() { var color = regex2.test(this.value) ? "red" : "green"; $(this).css({ borderColor: color, color: color }); }); /* AUTRES FONCTIONS */ function verifier(champ) { if (champ.val() == "") { $erreur.css('display', 'block'); champ.css({ borderColor: 'red', color: 'red' }); } } $envoie.click(function (e) { e.preventDefault(); verifier($nom); verifier($centre); verifier($magasin); verifier($profil); verifier($prenom); verifier($date); }); $centre.keypress(function () { if($(this).val().length > 2){ $(this).css({ borderColor: 'red', color: 'red' }); } else{ $(this).css({ borderColor: 'green', color: 'green' }); } }); $magasin.keypress(function () { if($(this).val().length > 2){ $(this).css({ borderColor: 'red', color: 'red' }); } else{ $(this).css({ borderColor: 'green', color: 'green' }); } }); $("#myForm").submit(function(e) { //e.preventDefault(); console.log("passage"); if ($("#myForm input.invalid").length > 0) { $("#logs").text("fail !"); return false; } $("#logs").text("success !") //return true; // laisse pour fonctionnement normal return false; }); });

Validating fields can be a tricky process to fully write out yourself. I would highly recommend the jQuery validate plugin.

It works like this:

 $(document).ready(function () { $('#myform').validate({ rules: { fieldOne: { required: true, email: true }, fieldTwo: { required: true, minlength: 5 } } }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script> <form id="myform"> <input type="text" name="fieldOne"> <input type="text" name="fieldTwo"> <input type="submit" value="save"> </form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM