admin管理员组文章数量:1410706
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;
}
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;
}
Share
Improve this question
asked Jan 25, 2014 at 6:53
user3066599user3066599
231 gold badge1 silver badge10 bronze badges
15
- The script tags are next the the closing body tag. – user3066599 Commented Jan 25, 2014 at 6:55
- It will not show an error – user3066599 Commented Jan 25, 2014 at 6:55
- Should I be using onclick – user3066599 Commented Jan 25, 2014 at 6:56
- should be checking the field on each "onkeyup" you could do the check onblur, or before submit. – Patrick Evans Commented Jan 25, 2014 at 6:56
- @PatrickEvans is onblur the perfered method – user3066599 Commented Jan 25, 2014 at 6:56
3 Answers
Reset to default 3If 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 es 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 pliment 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.
Alternative Way for modern browsers: Use html5 form validation (no JS required) for client side form validation — like so: <input type=text required minlength=8>
.
You 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 supposed 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>
本文标签: javascriptClient Side Form ValidationStack Overflow
版权声明:本文标题:javascript - Client Side Form Validation. - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745028111a2638326.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论