简体   繁体   中英

Client Side Form Validation.

So I have been trying to do client side Form Validation. I am trying to validate the first name and then will work on the rest. I assume that the Javascript should be checking the field on each "onkeyup" and show my message, "First Name Required" if there are no characters within that field. I will leave my form information below and then the validation code I am using afterward. I am running the script that links 'index.php' to 'validation.js' The script is in index.php next to the "" tag.

Thanks for any help I really do appreciate it.

<form method="POST" name="signup" action="php/processuserform.php">

<input id="firstname" onsubmit="validateFirstName()"  placeholder="First Name"  
type="text" /><label id="firstnameprompt"></label>

<br><br>

<input id="last_name" onkeyup="validateLastName()"  placeholder="Last Name" 
type="text" /><label id="last_nameprompt"></label>

<br><br>


<input id="email" onkeyup="validateEmail()"  placeholder="Email" type="text" /><label 
id="emailprompt"></label>

<br /><br />

<input id="password" onkeyup="validatePassword()"  placeholder="Create Password" 
type="password" /><label id="passwordprompt"></label>

<br /><br />

<strong>Male</strong><input id="male" value="male"  type="radio" /><label 
id="maleprompt"></label>

<strong>Female</strong><input id="female" value="female"  type="radio" /><label 
id="femaleprompt"></label>


<br /><br />

<label for="submit">"I Agree To <a href="#">Terms And Conditions"</a></label> <input 
id="submit" value="Submit" type="submit" name="submit"/><br /><br />

=======================================...

Now is the validation that I have been trying to use. Just trying to make sure the fields not empty.

function validateFirstName()
{
var name = document.getElementById("firstname").value;

if(name.length == 0)

{
producePrompt("First Name Required", "firstnameprompt", "red");
return false;

}
}

function producePrompt(message, promptlocation, color)
{
document.getElementById(promptLocation).innerHTML = message;
document.getElementById(promptLocation).style.color = color;

}

If all you want to do is make sure fields aren't empty, you can prevent a lot of duplication by giving your JavaScript a class that marks it as required.

<input id="firstname" class="required" placeholder="First Name" />

Notice I've removed the inline JavaScript and added our className. Now we can use one function that makes sure any input with className "required" has text in it.

The problem with this is that we can't really write nice clean validation messages for our catch-all JavaScript, besides something generic like "firstname is required" (which we could do by grabbing the id). We also don't have a way to customize where we put each validation message using our catch-all. That's where the data attribute comes in handy. So now our text box looks like:

<input id="firstname" class="required" placeholder="First Name" data-message="We need your first name!" data-prompt="firstnameprompt" />

The "data- _ " attribute is really handy for storing data that is specific to that element, so that we can use generic functions without sacrificing specificity. You can make as many as you want with any name you want (but do prepend the name with "data-" as a best practice. You could use them with regular expressions to really get specific, without having to write a ton of situation-specific JavaScript. Anyway, now we're ready to make one function that can do the job of ten.

var requireds = document.getElementsByClassName('required');
for(var i = 0, i < requireds.length; i++) { //for each required field
    requireds.addEventListener('keyup', function(event){
        //do stuff whenever this element changes
    });
}

Now we've attached listeners to each required textbox that will execute "//do stuff" whenever a users key goes up I that box. This replaces having to do it inline. The advantage is that if we decide to change the event that triggers validation, it's easy to do in one line instead of ten.

Speaking of events, now is when we need to think about the efficiency of the event we are using. In this example, every time there is a keyup in that field, it will look to see if it's blank. There are very few times when this would happen (delete and backspace, to name a few). Otherwise, most of the time, key up happens because the user is entering data into the field. So you are really only checking to see if the user has deleted existing text from the box. If they click submit without ever touching any text boxes, they will be allowed through. Not a very useful function, is it? Instead, we should change our event to form.submit. You may not like the sound of that because you want the feedback to be more instant, and I would agree, but that's code you can compliment to the form.submit event. If we were only allowed to use one event to validate, form submit is the one that is going to give the user the least likelihood of sending blank data. Submit.click is a close second, but the user could press enter and get through with blank data. So let's scrap the code above and do:

 var signupForm = document.getElementsByName('signup')[0];
 signupForm.addEventListener('submit', function(event){
    var requireds = document.getElementsByClassName('required');
    for (var i = 0; i < requireds.length; i++){
        if(requireds[i].value.length == 0){
              event.preventDefault(); //stop the form from submitting
              var errorMessage = requireds[i].getAttribute('data-message');
              var promptLabel = document.getElementsById(requireds[i].getAttribute('data-prompt'))[0];
              promptLabel.innerHTML = errorMessage;
        }
    }
    event.preventDefault(); //stop the form from submitting
    return errorMessage.length == 0;  //for older browsers, false if there's an error
  });

The above will validate the entire form, find the places it isn't valid, and put nicely formatted error messages in the prompt labels you have in place next to each. This is essentially how the JQuery.validate plugin works, except with way more cooler features.

Obligatory caveat on JavaScript validation: it should only be used as a convenience for your user for more instant feedback, or to save your server some extra load. A hacker/bot could easily bypass your signup page and send post headers directly to processesuserform.php, so your php should always do some strong validation/encoding before touching the database with any raw data that's posted to it.

现代浏览器的替代方法 :使用html5表单验证(不需要JS)进行客户端表单验证 - 如下所示: <input type=text required minlength=8>

u could do it easily by javascript

function validate(){
           var title=document.meetingform.subject.value;
           var status=false;
           if(title==""){
           document.getElementById("subjecterror").innerHTML=
           "Please enter your name";
           status=false;
           }else{
           document.getElementById("subjecterror").innerHTML="";
           status=true;
           }
           return status;
           }

In HTML you supose to have this:

<form name="meetingform" class="form-horizontal" action="<?php echo base_url();?>index.php/Notes/add_notes" onsubmit="return validate()" method="POST" enctype="multipart/form-data">
    <div class="form-body">
      <div class="form-group">
        <label class="control-label col-md-3">SUBJECT</label>
        <div class="col-md-9">
          <input name="subject" id="subject" placeholder="Title" class="form-control" type="text">
          <span id="subjecterror" name="subjecterror" style="color:#f00"></span>
        </div>
      </div>
<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